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

标签 javascript angularjs angularjs-ng-repeat

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

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>

app.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);
}

关于javascript - AngularJS 中数组拼接删除了错误的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27525906/

相关文章:

javascript - 通过选择标签值查找变量

javascript - 如何删除最后出现的匹配项?

javascript - 在调用 indexOf 定义的数组时,对象不支持 IE8 中未定义的此属性或方法

javascript - AngularJS 获取单个字段的 $pristine 状态

javascript - 添加新点时移动图表

javascript - redux 中的状态更新

javascript - 如何使用正式自定义模板初始化传单 map ?

angularjs - $ionicHistory 内部如何工作?

javascript - AngularJS ng-重复嵌套对象

javascript - 如何使用 ng-repeat-start 和 ng-repeat-end 从末尾删除附加图像?