AngularJS Focus & Blur Directives

Angular directives for blur and focus events.

by blesh

HTML

<div ng-controller="MyCtrl">
    <input type="text" placeholder="Focus me!" myng-focus="focused = true" myng-blur="focused = false" /> <pre ng-show="focused">I'm focused!!!</pre>

</div>

JavaScript

var myApp = angular.module('myApp', ['myDirectives']);

myApp.controller('MyCtrl', ['$scope', function ($scope) {}]);


(function (window, angular) {
    var module = angular.module('myDirectives', []);

    function addSimpleEventDirective(name) {
        var directiveName = 'myng' + name;
        module.directive(directiveName, ['$parse', function ($parse) {
            return function (scope, element, attr) {
                var fn = $parse(attr[directiveName]);
                element.bind(name.toLowerCase(), function (event) {
                    scope.$apply(function () {
                        fn(scope, {
                            $event: event
                        });
                    });
                });
            };
        }]);
    }

    angular.forEach(['Blur', 'Focus'], addSimpleEventDirective);
})(window, window.angular);