了解 ngRepeat 'track by' 表达式 [英] Understanding the ngRepeat 'track by' expression
问题描述
我很难理解 angularjs 中 ng-repeat 的 track by 表达式是如何工作的.文档非常稀缺:http://docs.angularjs.org/api/ng/directive/ng重复
您能否解释这两个代码片段在数据绑定和其他相关方面的区别?
with: track by $index
<!--names 是一个数组--><div ng-repeat="(key, value) in names track by $index"><input ng-model="value[key]">
没有(相同的输出)
<!--names 是一个数组--><div ng-repeat="(key, value) in names"><input ng-model="value[key]">
如果你的数据源有重复的标识符,你可以通过 $index
跟踪
eg: $scope.dataSource: [{id:1,name:'one'}, {id:1,name:'one too'}, {id:2,name:'two'}]
在使用id"作为标识符(重复 id:1)时,您不能迭代此集合.
不起作用:
//带有项目的东西...</元素>
但是你可以,如果使用 track by $index
:
//带有项目的东西...</元素>
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>
without (same output)
<!--names is an array-->
<div ng-repeat="(key, value) in names">
<input ng-model="value[key]">
</div>
You can track by $index
if your data source has duplicate identifiers
e.g.: $scope.dataSource: [{id:1,name:'one'}, {id:1,name:'one too'}, {id:2,name:'two'}]
You can't iterate this collection while using 'id' as identifier (duplicate id:1).
WON'T WORK:
<element ng-repeat="item.id as item.name for item in dataSource">
// something with item ...
</element>
but you can, if using track by $index
:
<element ng-repeat="item in dataSource track by $index">
// something with item ...
</element>
这篇关于了解 ngRepeat 'track by' 表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!