【问题标题】:How do I use $timeout service in a Directive?如何在指令中使用 $timeout 服务?
【发布时间】:2016-08-26 10:27:55
【问题描述】:

基本上,我想在 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());
          })
        }

      }
    });
})();

【问题讨论】:

标签: jquery angularjs angularjs-directive timeout angularjs-timeout


【解决方案1】:

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());
})

【讨论】:

    【解决方案2】:
    setInterval(function(){
        // code here
        $scope.$apply();
    }, 1000); 
    

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

    $timeout 是 Angular 版本会自动更新 DOM

    【讨论】:

    • 不鼓励使用$apply,它的使用模式不好,尽管$timeout 确实有助于更新bindings而不是DOM
    【解决方案3】:

    只需将 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());
              })
            }
    
          }
        });
    })();
    

    希望它对你有用。

    【讨论】:

    • 坏主意,你应该使用角度依赖,否则你将需要调用$apply方法来更新范围。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 2013-05-26
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多