ng-repeat 中的track by
<div style="font-size:15px"ng-repeat="item in groups.items track by $index"> <span>{{$index+1}}.</span> <span style="padding-left: 10px">{{item.name}}</span> <input ng-disabled = "item.firstSelected" style="vertical-align: middle;float:right;margin-right: 10px;" type="checkbox" ng-model="item.selected"> </div>
界面如图
track by $index 根据遍历循环的索引 创建唯一键防止数组相同元素时报错
我们见到最简单的例子是:
1
|
<div ng-repeat= "link in links" ></div> |
如果item的值有重复的,比如links=["1","1","2","2","3"]
那么angularjs 会报错,不允许值重复,原因是angular需要一个唯一值可以与生成的dom绑定,以便追踪.
然后这时候,track by的用处就体现出来了。
1
|
<div ng-repeat= "(key,value) in links track by key" ></div> |
key值是唯一的,这样就解决了