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/


You can do this with the built-in ngAttr attribute bindings.

<input ng-attr-autofocus="{{SOME_SCOPE_VARIABLE}}">

The autofocus attribute will be added if SOME_SCOPE_VARIABLE is defined (even if it's false), and will be removed if it's undefined. So I force falsy values to be undefined.

$scope.SOME_SCOPE_VARIABLE = someVar || undefined;

Tags:

Angularjs