如何使用AngularJS从ng-repeat中删除数组中的对象?

时间:2015-06-11 13:26:11

标签: angularjs ng-repeat

我有一个像[{...},{...}]这样的对象的数组,我用ng-repeat输出。然后我有一个删除按钮,其中包含删除它的功能。

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

6 个答案:

答案 0 :(得分:14)

如果您不应用过滤器来重新排序或过滤阵列,则可以执行以下操作:

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

删除功能:

$scope.items = [...];

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

另一种没有过滤问题的方法:(仅限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/

答案 1 :(得分:2)

这是另一个使用Jade的例子:

template.jade:

 label All Items
 ul.list-group
   li.list-group-item(ng-repeat="item in items | orderBy: '_id'")
    strong {{item.name}}
 a.trash(ng-click='deleteItem(item)')
//a.trash is a bootstrap trash icon, but you don't need to use it.

controller.js:

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

答案 2 :(得分:0)

首先尝试这样做,但列表未在运行时实现。

$scope.delete = function (index) {
    delete $scope.items[index];
}

然后, Facundo Pedrazzini 上面给出的答案确实适合我。

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

版本:AngularJS v1.6.4

答案 3 :(得分:0)

removeWith 将集合中的每个元素与给定属性对象进行比较, 返回一个数组,不包含所有具有相等属性值的元素。

isBaseline
  $scope.collection = [
    { id: 1, name: 'foo' },
    { id: 1, name: 'bar' },
    { id: 2, name: 'baz' }
  ]

<tr ng-repeat="obj in collection | removeWith:{ id: 1 }">
  {{ obj.name }}
</tr>

答案 4 :(得分:0)

在blade.php中

SELECT 
    ft.face_type,
    COUNT(ho.user_id) as cnt
FROM 
    (SELECT unnest(enum_range(NULL::face_type)) AS face_types) ft
    LEFT JOIN users us ON us.face_type = ft.fact_type
    LEFT JOIN houses ho ON ho.user_id = us.id
GROUP BY ft.face_type
UNION
SELECT
    null,
    COUNT(ho.user_id)
FROM houses ho
INNER JOIN users us ON ho.user_id = us.id AND us.face_type IS NULL
ORDER BY cnt desc

在controller.js中

<table style="width:100%;">
    <tr ng-repeat="name in planFormData.names track by $index">
        <td>
            <div class="form-group">
                <label>Plan Name<span style="color:red;">*</span> </label>
                <input type="text" class="form-control" ng-model="planFormData.names[$index].plan_name" name="plan_name" id="status-name" placeholder="Plan Name" autocomplete="off" required>
            </div>
        </td>
        <td>
           <a href="JavaScript:Void(0);"><i class="icon-plus" ng-click="addRow($index)" ng-show="$last"></i></a>
           <a href="JavaScript:Void(0);"><i class="icon-trash" ng-click="deleteRow($event,name)" ng-show="$index != 0"></i></a>
        </td>
    </tr>
</table>

答案 5 :(得分:0)

在Angular 6中,我对多维数组做了类似的操作。工作正常

  RemoveThisTimeSlot(i: number, j: number) {    
    this.service.formData.ConsultationModelInfo.ConsultationWeekList[i].TimeBlockList.splice(j, 1);
  }