{{$index}} 的 ng-repeat 在 angular 指令的链接器函数之后计算.$编译它? [英] {{$index}} of ng-repeat computed after linker function of angular directive. $compile it?

查看:15
本文介绍了{{$index}} 的 ng-repeat 在 angular 指令的链接器函数之后计算.$编译它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

html

<div repeater ng-repeat='item in items' class='first' id = '{{$index}}' > {{item}} </div>

angularjs 指令:-

angularjs directive:-

angular.module('time', [])
  .directive('repeater', function() {

    var linkFn = function(scope, element, attrs){
      var id = $(element).attr('id');
      alert(id); // {{$index}}
    } ...

在 ng-repeat 内部创建的动态 id,当在指令内部调用时显示为 {{$index}} 而不是 value = 0, 1, 2 ...

dynamic id created inside ng-repeat, when evoked inside directive displays as {{$index}} instead of value = 0, 1, 2 ...

你如何确保指令中的链接器函数在执行时使用了动态 id?我认为可以在指令中使用 $compile 来完成.但我不太明白怎么办?

How do you ensure when Linker function in directive executes the dynamic ids are used? I think it can be done using $compile inside the directive. But i can't quite figure how?

$compile(element)(scope) 

是语法.但显然顺序错误.

is the syntax. But obviously the wrong order.

推荐答案

如果您确实需要已经填充的 ID,您可以在 scope.$evalAsync$ 中运行相关代码timeout 以确保绑定已首先更新.我建议尽量避免需要检查 DOM,而是使用 scope.$index 依赖您的模型来获取任何这些信息.

If you really need the IDs to be already populated you can run the relevant code inside scope.$evalAsync or $timeout to make sure the binding has been updated first. I would suggest trying hard to avoid needing to inspect the DOM and relying instead on your model for any of this information, using scope.$index.

您的指令已在编译过程中,并在到达链接函数时进行链接,因此我认为重新编译无济于事.这只是一种等待足够长的时间来完成链接并开始一个 $digest 属性将被实际更新的情况.这正是 $evalAsync 将为您做的.

Your directive is already in the process of being compiled when and linked when your link function is reached so I think recompiling wouldn't help. It is just a case of waiting long enough to finish the linking and start a $digest where the attributes will actually be updated. This is exactly what $evalAsync will do for you.

此处示例:http://plnkr.co/edit/n77x4C?p=preview

这篇关于{{$index}} 的 ng-repeat 在 angular 指令的链接器函数之后计算.$编译它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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