HTML5: How to set focus on a text input in a list with AngularJS

后端 未结 4 1457
闹比i
闹比i 2020-12-11 18:37

I use AngularJS with the ng-repeat directive to show an array of objects as a list.

  • 4条回答
    •  夕颜
      夕颜 (楼主)
      2020-12-11 19:00

      The other proposed answers work OK 9/10 times for me, but soon I was running in "$digest already in progress" fun.

      I have a slightly modified version of the previous answers by asgoth and Mark Rajcok. Basically you inject the $timeout dependency and put the focus() call inside of a timeout(...). IIRC ng-focus does the same.

      var app = angular.module('cgeers', []);
      app.directive('focus', ["$timeout", function ($timeout) {
          return {
              restrict: 'A',
              link: function (scope, element, attrs) {
                  scope.$watch(attrs.focus, function (value) {
                      if (value) {
                          $timeout(function() { element[0].focus(); });
                      }
                  });
              }
          };
      }]);
      

    提交回复
    热议问题