亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

用angularJS做購物車清單點移除時總移除兩條數據?

用angularJS做購物車清單點移除時總移除兩條數據?

呼如林 2018-09-13 09:11:51
<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);         }     }); }
查看完整描述

1 回答

?
子衿沉夜

TA貢獻1828條經驗 獲得超3個贊

既然你決定通過 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?;蛘咛?nbsp;forEach 循環。這樣就不會刪除多個了


查看完整回答
反對 回復 2018-10-16
  • 1 回答
  • 0 關注
  • 618 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號