数组拼接删除了 AngularJS 中的错误元素

Array splice removes the wrong element in AngularJS

本文关键字:错误元素 AngularJS 拼接 删除 数组      更新时间:2023-09-26

我阅读了其他人的所有其他问题和答案,但仍然无法弄清楚。

.HTML:

<table class="table table-striped" ng-show="coffees.length>0">
                <thead>
                  <tr>
                    <th>Drink</th>
                    <th>Price</th>
                    <th>Number per week</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  <tr ng-repeat="c in coffees">
                    <td>{{c.type}}</td>
                    <td>{{c.price | currency:"&pound;"}}</td>
                    <td>{{c.numberpw}}</td>
                    <td><a href ng-click="removeCoffee($index)">X</a></td>
                  </tr>
                </tbody>
              </table>

应用.js:

var app = angular.module("calculator",[]);
app.controller('pageController',function($scope){       
    $scope.coffees=[];  
});
app.controller('coffeeController',function($scope){     
    $scope.addCoffee=function(coffee){      
        $scope.coffees.push(coffee);
        $scope.coffee={};
    }
    $scope.removeCoffee=function(el){       
        $scope.coffees.splice($scope.coffees[el],1);
    }
});

coffeeController 嵌套在 pageController 中,所以我可以在 coffeeController 中访问 $scope.coffees。addCoffee 函数接受如下所示的对象:

<select name="CoffeeType" ng-model="coffee.type" ng-options="type for type in 
['Espresso','Latte']" class="form-control" required>
<option value="">Please select</option>
</select>                      
<input type="text" placeholder="&pound;00.00" ng-pattern="/^0|[1-9][0-9]*$/" ng-model="coffee.price" name="CoffeePrice" class="form-control" required />
<select name="NumberPerWeek" class="form-control" ng-model="coffee.numberpw" ng-options="n for n in [1,2,3,4,5]" required>
<option value="">Please select</option>
</select>
<input type="submit" class="btn btn-primary pull-left" value="Add Drink" ng-click="addCoffee(coffee)" />

它完美地添加了对象,但每次都删除了错误的对象。

splice需要开始/计数整数。 $scope.coffees[el]是一个对象,但您正在将$index传递给该方法。更新删除方法,如下所示:

$scope.removeCoffee=function(el){       
    $scope.coffees.splice(el,1);
}