用法:ng-repeat="extension";
extension(表達式) 定義了如何循環集合。
表達式實例規則:
1. x in records
2. (key,value) in myObj
3. x in records track by $id(x)
我們可以使用ng-repeat指令遍歷一個JavaScript數組,當數組中有重復元素的時候,AngularJS會報錯:
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。
如下面的代碼就會報錯:
<!DOCTYPE html> <html ng-app="app" ng-controller="appCtrl"> <head> <title>Self Document</title> <script type="text/javascript" src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script> var app = angular.module('app',[]); app.controller('appCtrl',function($scope,$element){ $scope.dataList = [1,2,1]; }); </head> <body> <div ng-repeat="value in dataList"> <p> <span ng-bind="value"></span> </p> </div> </body> </html>
這是因為ng-repeat不允許集合中存在兩個相同id的對象。
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.
對於數字或者字符串等基本數據類型來說,它的id就是它自身的值。因此數組中是不允許存在兩個相同的數字的。為了規避這個錯誤,需要定義自己的track by表達式。
// 業務上自己生成唯一的id
1. item in items track by item.id
//或者直接拿循環的索引變量$index來用
2. item in items track by $index
另外:如果集合是Javascript對象類型數據,那么就算值一摸一樣,ng-repeat也不會認為這是相同的對象。
如果將上面的代碼中dataList,那么是不會報錯的。比如$scope.dataList = [{"num":10},{"num":10}];
參考文章:http://blog.csdn.net/aitangyong/article/details/44100921