Angularjs ng-repeat array - duplicate values

2019-04-26 18:32发布

问题:

So I'm just starting with angular JS and am a little confused about ng-repeat when dealing with arrays. The below code doesn't work as is...but when I change dayNames to an object and give it key value pairs it's fine.

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>

回答1:

It does not work as is because you have duplicates in the array. When you repeat array of primitives, the default unique key used by angular to associate the item in the array with the DOM element is the item in the array itself. And ofcourse in your case it is not unique and it causes duplicate in repeater error.

You could avoid this by using track by $index as well, which makes the index to be the identifier.

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

When you use array of objects (without track by) angular adds the unique id to a new property called $$hashkey on each item of the array. This property is then used as a key to associated DOM elements with the corresponding item in the array by identity. Moving the same object in array would move the DOM element in the same way in the DOM. So when you use array of objects you do not see any issues, because all of those hashkeys are unique.

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 track by $index">{{day}}</li>
	</ul>
</body>
	

</html>