【发布时间】:2015-08-27 05:27:36
【问题描述】:
我有一个包含 [{...}, {...}] 之类的对象的数组,我正在使用 ng-repeat 输出这些对象。然后我有一个删除按钮,带有删除它的功能。
有没有一种简单的方法可以在 AngularJS 中删除它,也许用 $index ?或者我需要在每个对象上指定一个 ID 作为属性?
【问题讨论】:
我有一个包含 [{...}, {...}] 之类的对象的数组,我正在使用 ng-repeat 输出这些对象。然后我有一个删除按钮,带有删除它的功能。
有没有一种简单的方法可以在 AngularJS 中删除它,也许用 $index ?或者我需要在每个对象上指定一个 ID 作为属性?
【问题讨论】:
在 Angular 6 中,我对多维数组做了类似的处理。它正在工作
RemoveThisTimeSlot(i: number, j: number) {
this.service.formData.ConsultationModelInfo.ConsultationWeekList[i].TimeBlockList.splice(j, 1);
}
【讨论】:
在blade.php中
<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>
在controller.js中
$scope.deleteRow = function($event, name) {
var index = $scope.planFormData.names.indexOf(name);
$scope.planFormData.names.splice(index, 1);
};
【讨论】:
removeWith 将集合中的每个元素与给定的属性对象进行比较, 返回一个没有所有具有等效属性值的元素的数组。
$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>
<tr ng-repeat="obj in collection | removeWith:{ id: 1, name: 'foo' }">
{{ obj.name }}
</tr>
【讨论】:
首先尝试这样做,但列表在运行时没有实现。
$scope.delete = function (index) {
delete $scope.items[index];
}
然后,Facundo Pedrazzini 上面给出的答案对我来说确实有效。
$scope.delete = function (index) {
$scope.items.splice(index, 1);
}
版本:AngularJS v1.6.4
【讨论】:
这是另一个例子,也使用 Jade:
模板.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);
}
【讨论】:
如果您不应用过滤器来重新排序或过滤您的数组,您可以这样做:
<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);
}
【讨论】: