Input autofocus attribute

后端 未结 10 1521
Happy的楠姐
Happy的楠姐 2020-11-30 04:47

I have places in my code where I have this:


I would like to be able to use it like

10条回答
  •  迷失自我
    2020-11-30 05:12

    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:

    
    

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

提交回复
热议问题