Input autofocus attribute

Update: AngularJS now has an ngFocus directive that evaluates an expression on focus, but I mention it here for the sake of completeness.


The current version of AngularJS doesn’t have a focus directive, but it’s in the roadmap. Coincidentally, we were talking about this on the mailing list yesterday, and I came up with this:

angular.module('ng').directive('ngFocus', function($timeout) {
    return {
        link: function ( scope, element, attrs ) {
            scope.$watch( attrs.ngFocus, function ( val ) {
                if ( angular.isDefined( val ) && val ) {
                    $timeout( function () { element[0].focus(); } );
                }
            }, true);

            element.bind('blur', function () {
                if ( angular.isDefined( attrs.ngFocusLost ) ) {
                    scope.$apply( attrs.ngFocusLost );

                }
            });
        }
    };
});

Which works off a scope variable as you requested:

<input type="text" ng-focus="isFocused" ng-focus-lost="loseFocus()">

Here’s a fiddle: http://jsfiddle.net/ANfJZ/39/

Leave a Comment