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

查看:19
本文介绍了如何使用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天全站免登陆