DOM在指令中未就绪's链接功能.hacky Timeout是唯一的解决方案吗

DOM is not ready in a directive's link function. Is hacky Timeout the only solution?

本文关键字:Timeout hacky 功能 唯一 解决方案 链接 指令 就绪 DOM      更新时间:2023-09-26

我在指令的模板中使用ng-repeat

myApp.directive("test", function () {
    return {
   restrict: 'C',
     scope: {
      bindVar: '='
    },
        template: '<div>'
<div class="item" ng-repeat="sel in bindVar">{{sel.display}}</div>'
     </div>',
     link: function ($scope, element, attrs) {

     //   setTimeout(function() { 
        alert($('.item').length); // <--- RETURNS 0, IF I ADD TIMEOUT RETURNS 3
   // },0);

     } // of link
    } // of return
});

http://jsfiddle.net/foreyez/t4590zbr/

但是,当调用link()函数时,我似乎无法访问已创建的项。为了做到这一点,我需要设置一个超时0(之后它就工作了)。

我在下面的文章中读到了这一点:http://lorenzmerdian.blogspot.com/2013/03/how-to-handle-dom-updates-in-angularjs.html

我还看到了一个类似的Stack Overflow答案,其中OP将Timeout标记为答案:AngularJS Directive';s链接()函数

但是拜托,一定还有别的办法!

我祈祷这个破解的解决方案是错误的,在通过指令创建DOM时,angular在某种程度上提供了回调。还是我真的依赖。。超时?(真的吗?:/)

事实上,当您使用内联template(而不是templateUrl)时,

$timeout是解决此问题的合法方法。这不会造成比赛条件。

实际情况是,Angular遍历DOM并收集指令及其链接前和链接后函数(通过编译指令)。然后,执行每个节点(即DOM元素)的每个指令的链接函数。

通常,节点的模板(指令应用于该节点)已经是DOM的一部分。因此,如果你有以下指令:

.directive("foo", function(){
  return {
    template: '<span class="fooClass">foo</span>',
    link: function(scope, element){
      // prints "<span class="fooClass">foo</span>"
      console.log(element.html()); 
    }
  }
}

它可以找到CCD_ 6元素。

但是,如果一个指令使用transclude: 'element',就像ng-if(ngIf.js)和ng-repeat(ngRepeat.js)指令一样,Angular会将该指令重写为注释(compile.js),因此$(".item")(在您的示例中)直到ng-repeat将其放在那里才存在。他们在scope.$watch函数(ngIf.js)中这样做,这取决于他们正在观察的值,这可能发生在下一个摘要周期。因此,即使您的post-link函数运行,您要搜索的实际元素仍然不存在。

.directive("foo", function(){
  return {
    template: '<span ng-if="true" class="fooClass">foo</span>',
    link: function(scope, element){
      // prints "<!-- ngIf: true -->"
      console.log(element.html());
    }
  }
}

但当$timeout运行时,它肯定会出现。

我这样做的方法是使用另一个指令。例如:

.directive('elementReady', function() {
   return {
       restrict: 'A',
       link: function(scope, elem, attr) {
           //In here, you can do things like:
           if(scope.$last) {
              //this element is the last element in an ng-repeat
           }
           if(scope.$first) {
              //first element in ng-repeat
           }
           //do jQuery and javascript calculations (elem has been added to the DOM at this point)
       }
   };
});

<table class="box-table" width="100%">
        <thead>
            <tr>
                <th class='test' scope="col" ng-repeat="column in listcolumns" element-ready>{{column.title}}</th>
            </tr>
        </thead>
</table>

显然,您需要自定义如何将这些事件传播到外部作用域($emit、通过绑定函数等)。

根据Joe的答案和我在stackoverflow上找到的另一个答案,我可以通过以下方式做到这一点:

myApp.directive('myRepeatDirective', function() {
  return function(scope, element, attrs) {
    if (scope.$last){
      scope.$emit('LastElem');
    }
  };
});

然后在我原来的链接功能中:

 $scope.$on('LastElem', function(event){
        alert($('.item').length);
    });

模板看起来像:

<div>
<div class="item" ng-repeat="sel in bindVar" my-repeat-directive>{{sel.display}}</div>
</div>

http://jsfiddle.net/foreyez/t4590zbr/3/

但我仍然不喜欢这个解决方案。。看起来有点像