为什么自动聚焦指令不起作用

时间:2017-08-04 14:54:37

标签: angularjs

自动对焦指令无法查看我的代码

我认为存在一些问题

var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope) {});
app.directive('autoFocus', ['$timeout', function ($timeout) {
return {
    restrict: 'AC',
    link: function (scope, element, attrs, ctrl) {
        setTimeout(function () {
            if ($(element)) {// if value is already filled 
                if (attrs.focusNext) { // if next Field provided then put focus on next field
                    var target = angular.element('#' + attrs.focusNext);
                    target.focus();
                }
                else element.focus();
            }
            else element.focus(); //setting current value focus
        }, 600);
    }
};
}])

2 个答案:

答案 0 :(得分:0)

我认为你需要把索引放在像这样的元素

app.directive('autoFocus', ['$timeout', function ($timeout) {
return {
    restrict: 'AC',
    link: function (scope, element, attrs, ctrl) {
        setTimeout(function () {
            if ($(element[0]).val()) {// if value is already filled 
                if (attrs.focusNext) { // if next Field provided then put focus on next field
                    var target = angular.element('#' + attrs.focusNext);
                    target[0].focus();
                }
                else element[0].focus();
            }
            else element[0].focus(); //setting current value focus
        }, 600);
    }
};
}])

希望它会帮助你

答案 1 :(得分:0)

正如@hope所说,你必须使用索引来访问DOM元素,但你还需要使用element[0].value来访问元素值。

最后,您需要使用angular.element(document.getElementById(attrs.focusNext))按ID查找元素,如下所示:



var app = angular.module('plunker', []);

app.directive('autoFocus', ['$timeout', function($timeout) {
  return {
    restrict: 'AC',
    link: function(scope, element, attrs, ctrl) {
      setTimeout(function() {
        if (element[0].value) { // if value is already filled 
          if (attrs.focusNext) { // if next Field provided then put focus on next field
            var target = angular.element(document.getElementById(attrs.focusNext));
            target[0].focus();
          } else element[0].focus();
        } else element[0].focus(); //setting current value focus
      }, 600);
    }
  };
}])

app.controller('MainCtrl', function($scope) {
  $scope.test = "first input already filled"
});

<script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>

<body ng-app="plunker" ng-controller="MainCtrl">
  <input ng-model="test" auto-focus focus-next="secondField">
  <input id="secondField">
</body>
&#13;
&#13;
&#13;