为什么angularjs(ng-repeat)允许在输入数组值是整数类型时第一次添加重复记录



片段 1:

  • 如果运行下面的代码,则无法添加重复记录。

var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope) {
$scope.products = ["1", "2", "3"];
$scope.addItem = function() {
$scope.products.push($scope.addMe);
}
});
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>
</head>
<body>
<div ng-app="myShoppingList" ng-controller="myCtrl">
<ul>
<li ng-repeat="x in products">{{x}}</li>
</ul>
<input ng-model="addMe">
<button ng-click="addItem()">Add</button>
</div>
<p>Write in the input field to add items.</p>
</body>
</html>

上面的代码片段抛出了一个错误

"[ngRepeat:dupes] 不允许在中继器中重复。使用"跟踪依据"表达式指定唯一键。重复器:产品中的 x,重复键:字符串:1,重复值:


片段 2:

  • 但是,如果您运行下面的代码片段,则可以在第一次添加重复值。但它不允许在第二次单击时添加重复值

var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope) {
$scope.products = [1, 2, 3];
$scope.addItem = function() {
$scope.products.push($scope.addMe);
}
});
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>
</head>
<body>
<div ng-app="myShoppingList" ng-controller="myCtrl">
<ul>
<li ng-repeat="x in products">{{x}}</li>
</ul>
<input ng-model="addMe">
<button ng-click="addItem()">Add</button>
</div>
<p>Write in the input field to add items.</p>
</body>
</html>


代码片段差异:

代码段 1-$scope.products = ["1", "2", "3"];//字符串值

代码段 2-$scope.products = [1, 2, 3];//整数值


问题:

  • 如果数组值string,为什么 angular 不允许在第一次添加重复值?
  • 如果数组值integer,为什么 angular 允许在第一次添加重复值
  • 如果数组值integer,为什么 angular 不允许第二次重复值

这是因为默认情况下输入类型是文本,因此是字符串,所以数字 2 不是字符串"2"的 equel

如果将类型编号添加到输入中

<input type="number" ng-model="addMe"> 

在第二个示例中,您将看到它不允许重复输入

var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope) {
$scope.products = [1, 2, 3];
$scope.addItem = function() {
$scope.products.push($scope.addMe);
}
});
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.js"></script>
</head>
<body>
<div ng-app="myShoppingList" ng-controller="myCtrl">
<ul>
<li ng-repeat="x in products">{{x}}</li>
</ul>
<input type="number" ng-model="addMe">
<button ng-click="addItem()">Add</button>
</div>
<p>Write in the input field to add items.</p>
</body>
</html>

Angular 需要跟踪中继器中的数组项。如果未指定跟踪依据字段,则它通过创建数组项的哈希进行跟踪。

基于上述,您的问题的答案如下

如果数组值是字符串,为什么 angular 不允许在第一次添加重复值?

它为重复值创建相同的哈希 - 因此,错误

如果数组值为整数,为什么 angular 允许在第一次添加重复值

因为当您再次输入时,它被视为字符串,因此具有不同的哈希值。

如果数组值为整数,为什么 angular 不允许第二次重复值

因为第一个条目被视为字符串,因此第二个条目被视为重复项。

我调试了代码并找到了以下几点

当您从输入框中添加值时,它会将其视为字符串,而不是数字。

在第一种情况下

它包含一个字符串列表。考虑您尝试添加 3。它将输入视为"3",即 已经存在,因此它会产生错误。

在秒情况下

你有一个数字数组。首次插入项目时 比如说 3,它将被添加为字符串。所以3(整数)不一样 "3"(字符串)。

最新更新