如何在指令中使用 $timeout 服务?

How do I use $timeout service in a Directive?

基本上,我想在 angular 操纵了 DOM 之后测量元素的宽度。所以我想为此使用 $timeout,但它总是让我出错。

HTML

   <div ng-app="github">
      <ul mynav>
        <li ng-repeat="nav in navItems">{{nav.name}}</li>
      </ul>

      </div>
    </div>

CSS

ul,li {
  display:inline-block;
}
li {
  margin-right:1em;
}

JS

(function() {
  angular.module('github', [])
    .directive('mynav', function($window) {
      return {
        restrict: 'A',
        link: function(scope, element, attrs, timeout) {
          scope.navItems = [{
            "name": "home"
          }, {
            "name": "link1"
          }, {
            "name": "link2"
          }, {
            "name": "link3"
          }];
          timeout(function() {
            console.log($(element).width());
          })
        }

      }
    });
})();

link 函数不是注入依赖项的正确位置。它定义了参数序列,如下所示。你不能把依赖放在那里。

link(scope, element, attrs, controller, transcludeFn) {

在指令 function 中注入 $timeout 依赖项。

(function() {
  angular.module('github', [])
    .directive('mynav', function($window, $timeout) { //<-- dependency injected here
      return {

然后只需在 link 函数中使用注入的 $timeout

$timeout(function() {
    console.log(element.width());
})

只需将超时替换为 setinterval,如下所示:

(function() {
  angular.module('github', [])
    .directive('mynav', function($window) {
      return {
        restrict: 'A',
        link: function(scope, element, attrs, timeout) {
          scope.navItems = [{
            "name": "home"
          }, {
            "name": "link1"
          }, {
            "name": "link2"
          }, {
            "name": "link3"
          }];
          setInterval(function() { // replpace 'timeout' with 'setInterval'
            console.log($(element).width());
          })
        }

      }
    });
})();

希望对你有用。

setInterval(function(){
    // code here
    $scope.$apply();
}, 1000); 

$apply 包含在内以提醒您,由于这是一个外部 jQuery 调用,您需要告诉 angular 更新 DOM。

$timeout 作为 angular 版本自动更新 DOM