[英]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.