Angularjs ng-repeat数组 - 重复值

时间:2015-02-22 02:25:21

标签: arrays angularjs ng-repeat

所以我只是从角度JS开始,在处理数组时对ng-repeat有点困惑。下面的代码不能正常工作......但是当我将dayNames更改为一个对象并给它键值对时,它很好。



var myApp = angular.module('exampleApp', []);

myApp.controller("dayCtrl",function($scope){
	$scope.dayNames = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday"];
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="exampleApp">
<head>
	<script src="angular.js"></script>
	<script src="controller.js"></script>	
</head>
<body ng-controller="dayCtrl">
	<h2>Hello, these are the days of the week</h2>
	<ul>
		<li ng-repeat="day in dayNames">{{day}}</li>
	</ul>
</body>
	

</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:17)

它不能正常工作,因为您在数组中有重复项。重复基元数组时,angular用于将数组中的项与DOM元素相关联的默认唯一键是数组本身中的项。在您的情况下,它不是唯一的,它会导致转发器错误重复。

您也可以使用track by $index来避免这种情况,这会使索引成为标识符。

ng-repeat="day in dayNames track by $index"

当您使用对象数组(没有跟踪)时,angular会将唯一ID添加到数组的每个项目上名为$$hashkey的新属性。然后,此属性用作关联DOM元素与按标识的数组中相应项的关键字。在数组中移动相同的对象将以相同的方式在DOM中移动DOM元素。因此,当您使用对象数组时,您看不到任何问题,因为所有这些hashkey都是唯一的。

&#13;
&#13;
var myApp = angular.module('exampleApp', []);

myApp.controller("dayCtrl",function($scope){
	$scope.dayNames = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday"];
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="exampleApp">
<head>
	<script src="angular.js"></script>
	<script src="controller.js"></script>	
</head>
<body ng-controller="dayCtrl">
	<h2>Hello, these are the days of the week</h2>
	<ul>
		<li ng-repeat="day in dayNames track by $index">{{day}}</li>
	</ul>
</body>
	

</html>
&#13;
&#13;
&#13;