如何从AngularJS中的范围中删除项目?

Bye*_*Bye 153 html javascript 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>
Run Code Online (Sandbox Code Playgroud)

相关控制器方法:

$scope.delete = function (person) {
  API.DeletePerson({ id: person.id }, function (success) {
    // I need some code here to pull the person from my scope.
  });
};
Run Code Online (Sandbox Code Playgroud)

我试着$scope.persons.pull(person)$scope.persons.remove(person).

虽然数据库已成功删除,但我无法从作用域中提取此项目,并且我不想对客户端已有的数据进行服务器方法调用,我只是想从范围中删除这一个人.

有任何想法吗?

Jos*_*ber 309

你必须找到的索引person你的persons数组,然后使用数组的splice方法:

$scope.persons.splice( $scope.persons.indexOf(person), 1 );
Run Code Online (Sandbox Code Playgroud)

  • 这是一个更好的答案; 在筛选列表时工作,以便视图中的索引与范围中的数组中的索引不同. (49认同)
  • 这确实是更好的答案.请注意,除了Andrew提到的过滤列表用例之外,此方法还涵盖了删除多个人的情况,并且这些删除的Ajax请求无序返回.如果您在Ajax调用返回之前使用了行索引,那么最终将删除错误的行. (5认同)
  • 在某些情况下更好,但是使用indexOf你必须迭代所有项目以找到正确的项目,在Josh答案中你可以更快地得到索引和项目 (4认同)

Jos*_*ler 257

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

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

视图:

<a ng-click="delete($index)">Delete</a>
Run Code Online (Sandbox Code Playgroud)

控制器:

$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);
  });
};
Run Code Online (Sandbox Code Playgroud)

  • 小心 - 如果您在视图中使用同一对象的多个ng重复(例如,计划任务,未安排的任务,完成的任务全部来自$ scope.tasks),则此基于索引的解决方案将无法工作,因为您将拥有多个项目指数2,3,4等 (13认同)
  • @AndrewKuklewicz - `indexOf`可能是一个更昂贵的操作; 没有过滤,这是完全没必要的.但是通过过滤,`indexOf`将是合适的方法. (4认同)

Max*_*tin 8

我会使用具有有用功能列表的Underscore.js库.

without

without_.without(array, *values)
Run Code Online (Sandbox Code Playgroud)

返回数组的副本,其中删除了所有值的实例.

_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
// => [2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

var res = "deleteMe";

$scope.nodes = [
  {
    name: "Node-1-1"
  },
  {
    name: "Node-1-2"
  },
  {
    name: "deleteMe"
  }
];

$scope.newNodes = _.without($scope.nodes, _.findWhere($scope.nodes, {
  name: res
}));
Run Code Online (Sandbox Code Playgroud)

请参阅JSFiddle中的演示.


filter

var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });

// => [2, 4, 6]
Run Code Online (Sandbox Code Playgroud)

$scope.newNodes = _.filter($scope.nodes, function(node) {
  return !(node.name == res);
});
Run Code Online (Sandbox Code Playgroud)

请参阅小提琴中的演示.


ceb*_*bor 7

$scope.removeItem = function() {
    $scope.items.splice($scope.toRemove, 1);
    $scope.toRemove = null;
};
Run Code Online (Sandbox Code Playgroud)

这对我有用!