我遇到了这段代码:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<script>
var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope) {
$scope.products = ["Milk", "Bread", "Cheese"];
// If I push a duplicate here, it will crash
});
</script>
<div ng-app="myShoppingList" ng-controller="myCtrl">
<ul>
<li ng-repeat="x in products">{{x}}<span ng-click="removeItem($index)">×</span></li>
</ul>
<input ng-model="addMe">
<button ng-click="addItem()">Add</button>
</div>
<p>Click the little x to remove an item from the shopping list.</p>
</body>
</html>
运行正常。但是,如果我在数组中推送一个重复元素,如下所示:
$scope.products.push("Milk");
应用程序将崩溃。那是为什么?
答案 0 :(得分:3)
如果阵列中有一些重复项,则需要跟踪它们。在track by $index
中使用ng-repeat
,如下所示:
<li ng-repeat="x in products track by $index">
这应该可以解决您的问题。有关详细信息,您可以浏览ng-repeat
(Tracking and Duplicates)的文档。