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



基本上,我想在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(){
    // code here
    $scope.$apply();
}, 1000); 

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

$timeout是一个有角度的版本,它会自动更新DOM

只需将timeout替换为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());
          })
        }
      }
    });
})();

希望它对你有用。

最新更新