用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);

        }

    });
}
阅读 2.3k
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 循环。这样就不会删除多个了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题