用angularJS做购物车清单点移除时总移除两条数据?

https://img3.mukewang.com/5bc587160001ac3c09720253.jpg

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

        }

    });
}


呼如林
浏览 605回答 1
1回答

子衿沉夜

既然你决定通过 index 来删除数据,为何不传入&nbsp;$index&nbsp;作为参数呢?//&nbsp;Controller:$scope.remove&nbsp;=&nbsp;function&nbsp;(index)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;$scope.card.splice(index,&nbsp;1); }//&nbsp;HTML:<button&nbsp;type="button"&nbsp;ng-click="remove($index)"&nbsp;class="btn&nbsp;btn-danger">移除</button>至于为什么会出现多次删除的情况,我是这么分析的:既然多次删除,一定是因为多次执行了&nbsp;splice。而执行&nbsp;splice&nbsp;只有一个原因,就是&nbsp;index !== -1。所以,对于你当前的代码,&nbsp;splice&nbsp;之后,至少需要把&nbsp;index&nbsp;设回 -1。或者跳出&nbsp;forEach&nbsp;循环。这样就不会删除多个了
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript