[英]Unable to add or remove elements from an array in AngularJS
您好:在AngularJS中,我的腳濕了。 我正在嘗試添加和刪除數組中的元素; 但是,即時通訊無法達到預期的效果。
foll是JSON結構:
$scope.masters = [
{
"name": "Wittgenstein",
"thoughts": ["thought 1", "thought 2", "thought 3"]
},
{
"name": "King",
"thoughts": ["thought 1", "thought 2", "thought 3"]
}
];
愚蠢的人。
任何輸入,不勝感激。 謝謝。
如@Mathew所建議,您應按如下方式介紹$index
的用法:
JS代碼:
$scope.input = [];
$scope.add = function(i) { // receiving index as param
$scope.masters[i].thoughts.push($scope.input[i]);
$scope.input[i] = '';
};
HTML代碼:
<div ng-repeat="master in masters">
<h1>{{ master.name }}</h1>
<ul>
<li ng-repeat="thought in master.thoughts">
{{ thought }} <button ng-click="remove($index)">Remove</button>
</li>
</ul>
<input type="text" ng-model="input[$index]">
<button type="submit" ng-click="add($index)">Add</button>
</div>
請參閱此Plunker工作示例
您需要指定母版的索引。 這樣的事情應該在remove函數中起作用:
$scope.masters[masterIndex].thoughts.splice(index, 1);
其中masterIndex是您要從中刪除想法的母版的索引
這是您plnkr的更新版本。
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js@1.4.0" data-semver="1.4.0" src="https://code.angularjs.org/1.4.0/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="demoController">
<div ng-repeat="master in masters track by $index">
<h1>{{ master.name }}</h1>
<ul>
<li ng-repeat="thought in master.thoughts track by $index">
{{ thought }} <button ng-click="remove(master, $index)">Remove</button>
</li>
</ul>
<input type="text" ng-model="input[$index]">
<button type="submit" ng-click="add($index)">Add</button>
</div>
</body>
</html>
請注意,我是如何將當前的master包含為remove函數的參數的。 這確保了正確的母版被拼接,因為JavaScript數組是通過引用傳遞的。 以下是更新的角度控制器。
var app = angular.module('app', []);
app.controller('demoController', ['$scope', function ($scope) {
$scope.input = [];
$scope.masters = [ {
"name": "Wittgenstein",
"thoughts": ["thought 1", "thought 2", "thought 3"]
}, {
"name": "King",
"thoughts": ["thought 1", "thought 2", "thought 3"]
}];
$scope.add = function(index) {
$scope.masters[index].thoughts.push($scope.input[index]);
$scope.input[index] = '';
};
$scope.remove = function(master, index) {
master.thoughts.splice(index, 1);
};
}]);
add函數似乎不是從輸入模型中選取值,但是那應該是一個綁定問題,而不是該函數無法正常工作。
我希望這有幫助。
問題是您需要傳遞給master索引的add和remove函數。 因為您這樣做:
$scope.masters.thoughts.splice(index, 1);
但是master是一個Array,因此您需要在該Array中選擇一個對象,例如
$scope.remove = function(masterIndex, thoughtsIndex) {
$scope.masters[masterIndex].thoughts.splice(thoughtsIndex, 1);
};
為了使此功能在您的HTML中起作用,您必須在內部ng-repeat內部使用父索引
<div ng-repeat="master in masters">
<h1>{{ master.name }}</h1>
<ul>
<li ng-repeat="thought in master.thoughts">
{{ thought }}
<button ng-click="remove($patent.index, $index)">
Remove
</button>
</li>
</ul>
<input type="text" ng-model="input">
<button type="submit" ng-click="add($index)">Add</button>
</div>
在Add函數中,您必須執行相同的操作才能獲得masters數組的$ index。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.