I read all the other questions by others and answers, but still can't figure it out..
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 is nested within pageController, so I can access $scope.coffees inside the coffeeController. And addCoffee function accepts an object that looks like this:
<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)" />
It adds objects perfectly but removes the wrong object every single time..
splice
expects start/count integers. $scope.coffees[el]
is an object but you're passing in the $index
to the method. Update your remove method as follows:
$scope.removeCoffee=function(el){
$scope.coffees.splice(el,1);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.