如何从 AngularJS 范围内的数组中删除项目? [英] How to remove an item from an array in AngularJS scope?

查看:30
本文介绍了如何从 AngularJS 范围内的数组中删除项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单的待办事项列表,但在每个项目的列表页面上都有一个删除按钮:

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.拼接.此外,当使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆