如何从AngularJS作用域中的数组中删除项目? [英] How to remove an item from an array in AngularJS scope?
问题描述
简单的待办事项列表,但每个项目的列表页面上都有一个删除按钮:
Simple to-do list, but with a delete button on list page for each item:
相关模板HTML:
<tr ng-repeat="person in persons">
<td>{{person.name}} - # {{person.id}}</td>
<td>{{person.description}}</td>
<td nowrap=nowrap>
<a href="#!/edit"><i class="icon-edit"></i></a>
<button ng-click="delete(person)"><i class="icon-minus-sign"></i></button>
</td>
</tr>
相关控制器方法:
$scope.delete = function (person) {
API.DeletePerson({ id: person.id }, function (success) {
// I need some code here to pull the person from my scope.
});
};
我尝试了$scope.persons.pull(person)
和$scope.persons.remove(person)
.
尽管数据库已成功删除,但是我不能从范围中删除该项目,也不想对服务器进行方法调用以获取客户端已经拥有的数据,我只想从范围中删除此人.
Although the database deleted successfully, I can not pull this item from scope and I do not want to make a method call to the server for data the client already has, I just want to remove this one person from scope.
有什么想法吗?
推荐答案
您的问题不是Angular,而是Array方法.从数组中删除特定项目的正确方法是使用 Array.splice
一个>.另外,在使用ng-repeat时,您可以访问特殊的$index
属性,该属性是您传入的数组的当前索引.
Your issue is not really with Angular, but with Array methods. The proper way to remove a particularly item from an array is with Array.splice
. Also, when using ng-repeat, you have access to the special $index
property, which is the current index of the array you passed in.
该解决方案实际上非常简单:
The solution is actually pretty straightforward:
查看:
<a ng-click="delete($index)">Delete</a>
控制器:
$scope.delete = function ( idx ) {
var person_to_delete = $scope.persons[idx];
API.DeletePerson({ id: person_to_delete.id }, function (success) {
$scope.persons.splice(idx, 1);
});
};
这篇关于如何从AngularJS作用域中的数组中删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!