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

Art*_*der 6 jquery timeout angularjs angularjs-directive angularjs-timeout

基本上,我想在角度操纵DOM之后测量元素的宽度.所以我想使用$ timeout,但它一直让我犯错误.

HTML

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

      </div>
    </div>
Run Code Online (Sandbox Code Playgroud)

CSS

ul,li {
  display:inline-block;
}
li {
  margin-right:1em;
}
Run Code Online (Sandbox Code Playgroud)

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

      }
    });
})();
Run Code Online (Sandbox Code Playgroud)

Pan*_*kar 10

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

link(scope, element, attrs, controller, transcludeFn) {
Run Code Online (Sandbox Code Playgroud)

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

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

然后只使用注入$timeout内部link函数

$timeout(function() {
    console.log(element.width());
})
Run Code Online (Sandbox Code Playgroud)