Javascript 如何从 AngularJS 范围内的数组中删除项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14250642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:10:18  来源:igfitidea点击:

How to remove an item from an array in AngularJS scope?

javascripthtmlangularjs

提问by Bye

Simple to-do list, but with a delete button on list page for each item:

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

enter image description here

在此处输入图片说明

Relevant template HTML:

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

Relevant controller method:

相关控制器方法:

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

I tried $scope.persons.pull(person)and $scope.persons.remove(person).

我试过$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.

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

Any ideas?

有任何想法吗?

回答by Joseph Silber

You'll have to find the index of the personin your personsarray, then use the array's splicemethod:

您必须personpersons数组中找到 的索引,然后使用数组的splice方法:

$scope.persons.splice( $scope.persons.indexOf(person), 1 );

回答by Josh David Miller

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 $indexproperty, which is the current index of the array you passed in.

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

The solution is actually pretty straightforward:

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

View:

看法:

<a ng-click="delete($index)">Delete</a>

Controller:

控制器:

$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);
  });
};

回答by Maxim Shoustin

I would use the Underscore.jslibrary that has a list of useful functions.

我将使用具有有用函数列表的Underscore.js库。

without

without

without_.without(array, *values)

Returns a copy of the array with all instances of the values removed.

_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
// => [2, 3, 4]
without_.without(array, *values)

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

_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
// => [2, 3, 4]

Example

例子

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
}));

See Demo in JSFiddle.

请参阅JSFiddle 中的演示。



filter

filter

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

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

// => [2, 4, 6]

Example

例子

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

See Demo in Fiddle.

请参阅Fiddle 中的演示。

回答by cebor

$scope.removeItem = function() {
    $scope.items.splice($scope.toRemove, 1);
    $scope.toRemove = null;
};

this works for me!

这对我有用!

回答by Drako

If you have any function associated to list ,when you make the splice function, the association is deleted too. My solution:

如果你有任何关联到 list 的功能,当你做拼接功能时,关联也会被删除。我的解决方案:

$scope.remove = function() {
    var oldList = $scope.items;
    $scope.items = [];

    angular.forEach(oldList, function(x) {
        if (! x.done) $scope.items.push( { [ DATA OF EACH ITEM USING oldList(x) ] });
    });
};

The list param is named items. The param x.doneindicate if the item will be deleted.

列表参数名为items。参数x.done指示项目是否将被删除。

Another references: Another example

另一个参考:另一个例子

Hope help you. Greetings.

希望能帮到你。你好。

回答by gabn88

For the the accepted answer of @Joseph Silber is not working, because indexOf returns -1. This is probably because Angular adds an hashkey, which is different for my $scope.items[0] and my item. I tried to resolve this with the angular.toJson() function, but it did not work :(

对于@Joseph Silber 的公认答案不起作用,因为 indexOf 返回 -1。这可能是因为 Angular 添加了一个哈希键,这对于我的 $scope.items[0] 和我的项目是不同的。我试图用 angular.toJson() 函数解决这个问题,但它没有用:(

Ah, I found out the reason... I use a chunk method to create two columns in my table by watching my $scope.items. Sorry!

啊,我找到了原因...我使用块方法通过查看我的 $scope.items 在我的表中创建两列。对不起!

回答by Chetann

You can also use this

你也可以用这个

$scope.persons = $filter('filter')($scope.persons , { id: ('!' + person.id) });

回答by Taran

array.splice(array.pop(item));

回答by Allen

Angular have a built-in function called arrayRemove, in your case the method can simply be:

Angular 有一个名为 的内置函数arrayRemove,在您的情况下,该方法可以简单地为:

arrayRemove($scope.persons, person)

回答by Cubiczx

To remove a element from scope use:

要从作用域中删除元素,请使用:

// remove an item
    $scope.remove = function(index) {
        $scope.items.splice(index, 1);
    };

From enter link description here

这里输入链接描述