AngularJS ng-repeat數(shù)組有重復值的解決方法
前言
大家都知道默認在ng-repeat的時候每一個item都要保證是唯一的,否則console就會打出error告訴你哪個key/value是重復的。
如:
$scope.items = [ 'red', 'blue', 'yellow', 'white', 'blue' ];
這個數(shù)組blue就重復了,html這么遍歷它
<li ng-repeat="item in items">{{ item }}</li>
控制臺就會拋出一個錯誤:

點擊錯誤鏈接到Angular官網(wǎng)看詳細錯誤,官網(wǎng)明確給出是因為值重復了:
Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: item in items, Duplicate key: string:blue, Duplicate value: blue
解決方法
這就納悶了,正常的業(yè)務里數(shù)組有重復的值是很正常的,數(shù)組要硬要搞成唯一的ng-repeat才能遍歷就白瞎了,繼續(xù)往下看,發(fā)現(xiàn)官網(wǎng)給了一個解決的方案
<div ng-repeat="value in [4, 4] track by $index"></div>
于是按照這個方案改了一下
<li ng-repeat="item in items track by $index">{{ item }}</li>
刷新網(wǎng)頁,內(nèi)容被正常解析

其實ng-repeat還是需要一個唯一的key,只不過你不track的話默認就是item本身,另外也只有在普通數(shù)據(jù)類型字符串,數(shù)字等才會出現(xiàn)這個問題,如果換成Object
$scope.items = [ ['red'], ['blue'], ['yellow'], ['white'], ['blue'] ];
html恢復為
<li ng-repeat="item in items">{{ item }}</li>
執(zhí)行結果:

不明白的童鞋那就自己看看下面的運算表達式,猜猜結果是什么,然后在瀏覽器的控制臺試一試你的答案是否正確
[] === []
總結
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。
相關文章
AngularJS實現(xiàn)頁面跳轉(zhuǎn)后自動彈出對話框?qū)嵗a
這篇文章主要介紹了AngularJS實現(xiàn)頁面跳轉(zhuǎn)后自動彈出對話框?qū)嵗a,然后在文章下面給大家介紹了angularjs頁面加載后自動彈窗的實例代碼,感興趣的朋友參考下吧2017-08-08
Angularjs中$http以post請求通過消息體傳遞參數(shù)的實現(xiàn)方法
這篇文章主要介紹了Angularjs中$http以post請求通過消息體傳遞參數(shù)的方法,結合實例形式分析了$http使用post請求傳遞參數(shù)的相關設置與使用技巧,需要的朋友可以參考下2016-08-08

