如果 ng-model 未更改,则无法使用 ng-click 将项目推送到 javascript 数组
Cannot push item to javascript array using ng-click if the ng-model does not change
我可以通过 ng-click 事件处理将项目(通过 html 输入)动态添加到无序列表。每当我更改输入文本框值时都会发生这种情况。但是,如果我在不更新文本框的情况下单击添加按钮,则输入的文本框值不会添加到列表中。
<body>
<script>
var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope) {
$scope.products = ["Milk", "Bread", "Cheese"];
$scope.addItem = function () {
$scope.products.push($scope.addMe);
}
});
</script>
<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>
您需要像下面这样添加 track by $index
。 AngularJS
不允许在 ng-repeat
指令中重复。如果您尝试这样做,您将收到错误消息。
如果你想允许重复,你需要像下面这样更改你的代码。
<li ng-repeat="x in products track by $index">{{x}}</li>
例子
var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope) {
$scope.products = ["Milk", "Bread", "Cheese"];
$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 track by $index">{{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>
我可以通过 ng-click 事件处理将项目(通过 html 输入)动态添加到无序列表。每当我更改输入文本框值时都会发生这种情况。但是,如果我在不更新文本框的情况下单击添加按钮,则输入的文本框值不会添加到列表中。
<body>
<script>
var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope) {
$scope.products = ["Milk", "Bread", "Cheese"];
$scope.addItem = function () {
$scope.products.push($scope.addMe);
}
});
</script>
<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>
您需要像下面这样添加 track by $index
。 AngularJS
不允许在 ng-repeat
指令中重复。如果您尝试这样做,您将收到错误消息。
如果你想允许重复,你需要像下面这样更改你的代码。
<li ng-repeat="x in products track by $index">{{x}}</li>
例子
var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope) {
$scope.products = ["Milk", "Bread", "Cheese"];
$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 track by $index">{{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>