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

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

问题描述

我有一个指令附加到模板内动态生成的

元素.该指令在 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 */
        }
    };
});

推荐答案

从一般意义上说,您不能通过在

元素.

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 数组还不存在怎么办?或者如果有一个 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天全站免登陆