javascript - 用angularJS做购物车清单点移除时总移除两条数据?
本文介绍了javascript - 用angularJS做购物车清单点移除时总移除两条数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
<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
作为参数呢?
// Controller:
$scope.remove = function (index) {
$scope.card.splice(index, 1);
}
// HTML:
<button type="button" ng-click="remove($index)" class="btn btn-danger">移除</button>
至于为什么会出现多次删除的情况,我是这么分析的:既然多次删除,一定是因为多次执行了 splice
。而执行 splice
只有一个原因,就是 index !== -1
。
所以,对于你当前的代码, splice
之后,至少需要把 index
设回 -1。或者跳出 forEach
循环。这样就不会删除多个了
这篇关于javascript - 用angularJS做购物车清单点移除时总移除两条数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文