如何使用AngularJS从ng-repeat中的数组中删除对象? [英] How to remove object from array within ng-repeat with AngularJS?

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

问题描述

我有一个对象数组,例如[{...},{...}],我用ng-repeat输出.然后,我有一个具有删除功能的删除按钮.

I am having an array with objects like [{...}, {...}] which I am outputting with ng-repeat. Then I have a delete button with a function to delete it.

是否有一种简单的方法可以在AngularJS中将其删除,也许可以使用$ index?还是我需要在每个对象上指定一个ID作为属性?

Is there a simple way to delete it in AngularJS, perhaps with $index? Or I need to specify an ID on every object as an property?

推荐答案

如果不应用过滤器对数组进行重新排序或过滤,则可以执行以下操作:

If you don't apply a filter to reorder or filter your array, you can do this:

<div ng-repeat="item in items" ng-click="delete($index)">{{item}}</div>

删除功能:

$scope.items = [...];

$scope.delete = function (index) {
    $scope.items.splice(index, 1);
}

另一种没有过滤器问题的方法:(仅限IE9 +)

Another way to do it without filter problems: (ONLY IE9+)

<div ng-repeat="item in items | orderBy: 'id'" ng-click="delete(item)">{{item}}</div>

删除功能:

$scope.items = [...];

$scope.delete = function (item) {
    $scope.items.splice($scope.items.indexOf(item), 1);
}

http://jsfiddle.net/oymo9g2f/2/

这篇关于如何使用AngularJS从ng-repeat中的数组中删除对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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