<tr ng-repeat="item in cart">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.quantity}}</td>
<td>{{item.price}}</td>
<td>{{item.quantity * item.price}}</td>
<td>
<button type="button" ng-click="remove(item.id)" class="btn btn-danger">移除</button>
</td>
一下是JS部分:
$scope.remove = function (ids) {
var index = -1;
//console.log(ids);
angular.forEach($scope.cart, function (item,key) {
console.log(key);
if(item.id===ids){
index =key;
}
if(index!==-1){
$scope.cart.splice(index,1);
}
});
}
既然你决定通过 index 来删除数据,为何不传入
$index
作为参数呢?至于为什么会出现多次删除的情况,我是这么分析的:既然多次删除,一定是因为多次执行了
splice
。而执行splice
只有一个原因,就是index !== -1
。所以,对于你当前的代码,
splice
之后,至少需要把index
设回 -1。或者跳出forEach
循环。这样就不会删除多个了