理解ngRepeat'track by'表达式 [英] Understanding the ngRepeat 'track by' expression

查看:218
本文介绍了理解ngRepeat'track by'表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解angularjs中ng-repeat的跟踪表达方式是如何工作的。文档非常稀缺: http://docs.angularjs.org/api/ng/directive / ngRepeat

I'm having difficulties understanding how the track by expression of ng-repeat in angularjs works. The documentation is very scarce: http://docs.angularjs.org/api/ng/directive/ngRepeat

您能解释这两段代码之间的区别在于数据绑定和其他相关方面吗?

Can you explain what the difference between those two snippets of code is in terms of databinding and other relevant aspects?

with: track by $ index

<!--names is an array-->
<div ng-repeat="(key, value) in names track by $index">
  <input ng-model="value[key]">                         
</div>

没有(相同的输出)

<!--names is an array-->
<div ng-repeat="(key, value) in names">
   <input ng-model="value[key]">                         
</div>


推荐答案

您可以跟踪$ index 如果您的数据源有重复的标识符

You can track by $index if your data source has duplicate identifiers

例如: $ scope.dataSource:[{id:1,name :'one'},{id:1,name:'one too'},{id:2,name:'two'}]

使用'id'作为标识符时,您无法迭代此集合(重复ID:1)。

You can't iterate this collection while using 'id' as identifier (duplicate id:1).

将无效:

<element ng-repeat="item.id as item.name for item in dataSource">
  // something with item ...
</element>

但如果使用跟踪$ index

<element ng-repeat="item in dataSource track by $index">
  // something with item ...
</element>

这篇关于理解ngRepeat'track by'表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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