小编典典

如何从AngularJS作用域中的数组中删除项目?

angularjs

相关模板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)

尽管数据库已成功删除,但我无法从作用域中删除此项目,也不想对服务器进行方法调用以获取客户端已拥有的数据,我只想从作用域中删除此人。

有任何想法吗?


阅读 247

收藏
2020-07-04

共1个答案

小编典典

您的问题不是Angular,而是Array方法。从数组中删除特定项目的正确方法是使用Array.splice。另外,使用ng-
repeat时,您可以访问特殊$index属性,该属性是您传入的数组的当前索引。

该解决方案实际上非常简单:

视图:

<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);
  });
};
2020-07-04