最近在开发过程中,发现一个问题,在使用angularjs的ng-repeat遍历过程中,如果遍历的数组中包含相同的项,则会抛错。
如下例:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>测试</title>
<script src="http://cdn.bootcss.com/angular.js/1.4.8/angular.js"></script>
</head>
<body>
<p ng-repeat="item in names">
{{item}}
</p>
<p ng-repeat="item in ages">
{{item}}
</p>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.run(function($rootScope) {
$rootScope.names = ['ligang', 'fenfei', 'camile'];
$rootScope.ages = [25, 24, 25];
});
</script>
</body>
</html>
抛错:
Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use
‘track by’ expression to specify unique keys. Repeater: item in ages,
Duplicate key: number:25, Duplicate value: 25
解决方案:在对应的ng-repeat指令中增加track by $index
<p ng-repeat="item in ages track by $index">
{{item}}
</p>