AngularJS指令在元素完全加载之前运行 [英] AngularJS directive runs before element is fully loaded

查看:126
本文介绍了AngularJS指令在元素完全加载之前运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个附加到模板内动态生成的<table>元素的指令.该指令在link函数中操纵该表的DOM.问题在于该指令在呈现表之前运行(通过评估ng-repeat指令)-则表为空.

I have a directive attached to a dynamically generated <table> element inside a template. The directive manipulates the DOM of that table inside a link function. The problem is that the directive runs before the table is rendered (by evaluating ng-repeat directives) - the table is empty then.

问题

如何确保在完全渲染表格后运行指令?

How can I make sure that the directive is ran after the table has been fully rendered?

<table directive-name>
    <tr ng-repeat="...">
        <td ng-repeat="..."></td>
    </tr>
</table>


module.directive("directiveName", function() {
    return {
        scope: "A",
        link: function(scope, element, attributes) {
            /* I need to be sure that the table is already fully
               rendered when this code runs */
        }
    };
});

推荐答案

在一般意义上,仅对<table>元素设置指令就无法完全确定".

You can't, in a general sense, be ever "fully sure" by just having a directive on the <table> element.

但是在某些情况下您可以确定.在您的情况下,如果内部内容是ng-repeat -ed,那么如果准备好处理ngRepeat的项目数组,则实际的DOM元素将在摘要周期结束时准备好.您可以在$timeout之后以0的延迟捕获它:

But you can be sure in certain cases. In your case, if the inner content is ng-repeat-ed, then if the array of items over which ngRepeat works is ready, then the actual DOM elements will be ready at the end of the digest cycle. You can capture it after $timeout with 0 delay:

link: function(scope, element){
  $timeout(function(){
    console.log(element.find("tr").length); // will be > 0
  })
}

但是,从一般意义上讲,您不能确定要捕获的内容.如果ngRepeat ed数组还不存在怎么办?还是如果有ng-include呢?

But, in a general sense, you can't be certain to capture the contents. What if the ngRepeated array is not there yet? Or what if there is an ng-include instead?

<table directive-name ng-include="'templates/tr.html'">
</table>

或者,如果存在一个与ngRepeat不同的自定义指令,该怎么办?

Or, what if there was a custom directive that worked differently than ngRepeat does?

但是,如果您完全控制内容,一种可能的了解方法是将一些辅助指令作为最里面/最后一个元素,并在链接时与它的父directiveName联系:

But if you have full control of the contents, one possible way to know is to include some helper directive as the innermost/last element, and have it contact its parent directiveName when it's linked:

<table directive-name>
    <tr ng-repeat="...">
        <td ng-repeat="...">
          <directive-name-helper ng-if="$last">
        </td>
    </tr>
</table>

.directive("directiveNameHelper", function(){
  return {
    require: "?^directiveName",
    link: function(scope, element, attrs, ctrl){
      if (!ctrl) return;

      ctrl.notifyDone();
    }
  }
})

这篇关于AngularJS指令在元素完全加载之前运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆