我通过别人和答案阅读了所有其他问题,但仍然无法弄清楚..
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:"£"}}</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="£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)" />
它可以完美地添加对象,但每次都会删除错误的对象..
答案 0 :(得分:2)
splice
期望开始/计数整数。 $scope.coffees[el]
是一个对象,但您正在将$index
传递给该方法。更新您的删除方法,如下所示:
$scope.removeCoffee=function(el){
$scope.coffees.splice(el,1);
}