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>
And the above snippet throws an error for
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>
Snippet 1 - $scope.products = ["1", "2", "3"];
// string values
Snippet 2 - $scope.products = [1, 2, 3];
// integer values
string
?integer
integer
It is because by default input type is text therefore string, so number 2 is not equel to string "2"
if you add type number to your input
<input type="number" ng-model="addMe">
in your 2nd example you would see that it will not allow duplicate entry
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>
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加