Fragment 1:
- If you run this code below, you will not be able to add duplicate entries.
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>
Run codeHide resultAnd the above snippet throws an error for
[ngRepeat: dupes] Duplicates in the repeater are not allowed. Use the expression 'track by' to specify unique keys. Repeater: x in products, Duplicate key: string: 1, Duplicate value:
Fragment 2:
- But you can add a duplicate value for the first time if you run this snippet below. But it does not allow adding duplicate values ββby clicking a second time .
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>
Run codeHide result
Fragment code difference:
1 - $scope.products = ["1", "2", "3"];//
2 - $scope.products = [1, 2, 3];//
:
- angular ,
string? - angular ,
integer - angular ,
integer