Input autofocus attribute

后端 未结 10 1544
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:21

    I did it with two custom directives, something like this:

    (function(angular) {
      'use strict';
    
      /* @ngInject */
      function myAutoFocus($timeout) {
        return {
          restrict: 'A',
          link: function(scope, element) {
            $timeout(function() {
              element[0].focus();
            }, 300);
          }
        };
      }
    
      function myFocusable() {
        return {
          restrict: 'A',
          link: function(scope, element, attrs) {
            var focusMethodName = attrs.myFocusable;
            scope[focusMethodName] = function() {
              element[0].focus();
            };
          }
        };
      }
    
      angular
        .module('myFocusUtils', [])
        .directive('myAutoFocus', myAutoFocus)
        .directive('myFocusable', myFocusable);
    
    }(angular));
    

    If you add attribute my-auto-focus to an element, it will receive focus after 300ms. I set the value to 300 instead of 0 to let other async components to load before setting the focus.

    The attribute my-focusable will create a function in the current scope. This function will set focus to the element when called. As it creates something in the scope, be cautious to avoid overriding something.

    This way you don't need to add something to Angular's digest cycle (watch) and can do it entirely in the view:

            
    
    

    I created a JSFiddle to show the myFocusable directive: http://jsfiddle.net/8shLj3jc/

    For some reason I don't know, the myAutoFocus directive does not work in JSFiddle, but it works in my page.

提交回复
热议问题