{{$index}} 的 ng

编程入门 行业动态 更新时间:2024-10-09 02:26:53
本文介绍了{{$index}} 的 ng-repeat 在 angular 指令的链接器函数之后计算.$编译它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-21 18:51:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1007779.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:index   ng

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!