AngularJS: 'Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys."原因及解決辦法

原因及現(xiàn)象

我們可以使用ng-repeat指令遍歷一個(gè)JavaScript數(shù)組,當(dāng)數(shù)組中有重復(fù)元素的時(shí)候,AngularJS會(huì)報(bào)錯(cuò):
Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: user in users, Duplicate key: number:1。下面的代碼就會(huì)報(bào)錯(cuò):

<html>
<head>
<script src="angular-1.2.2/angular.js"></script>
<script>
function rootController($scope,$rootScope,$injector)
{
$scope.dataList = [1,2,1];
}
</script>
</head>
<body ng-app ng-controller="rootController">
<div ng-repeat="data in dataList">
{{data}}
</div>
</body>
</html>

這是因?yàn)閚g-Repeat不允許collection中存在兩個(gè)相同Id的對(duì)象。
For example: item in items is equivalent to item in items track by $id(item). This implies that the DOM elements will be associated by item identity in the array.
對(duì)于數(shù)字或者字符串等基本數(shù)據(jù)類型來說,它的id就是它自身的值。因此數(shù)組中是不允許存在兩個(gè)相同的數(shù)字的。為了規(guī)避這個(gè)錯(cuò)誤,需要定義自己的track by表達(dá)式。
// 業(yè)務(wù)上自己生成唯一的iditem in items track by item.id
//或者直接拿循環(huán)的索引變量$index來用item in items track by $index

如果是javascript對(duì)象類型數(shù)據(jù),那么就算內(nèi)容一摸一樣,ng-repeat也不會(huì)認(rèn)為這是相同的對(duì)象。如果將上面的代碼中dataList,那么是不會(huì)報(bào)錯(cuò)的。比如$scope.dataList = [{"age":10},{"age":10}];

解決辦法

  • 在循環(huán)的數(shù)組后面加上 track by $index 即可以完美解決

<li ng-repeat="x in names track by $index">

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容