Reputation: 571
I have an Angular app I am trying to get working correctly. Apparently there is just one more line of code that will make it work but I don't know what it is. I am still learning Angular and I'm not that good at Javascript anyway. I've made it so that anything entered into the input gets added to the list. But when I click a button to delete an item, it just deletes all of them. What can I do to fix it?
<body ng-app="myApp">
<div ng-controller="GroceryController">
<header>
<h1>Matt's Grocery List</h1>
<div>
<form ng-submit="addItem()">
<div>
<input type="text" ng-model="newItem" placeholder="New things">
<button type="submit">Save</button>
</div>
</form>
</div>
</header>
<section id="list">
<p>"{{ newItem }}"</p>
<div>
<h4>{{ groceries.length }} total items</h4>
<table>
<tr ng-repeat="gro in groceries">
<td>{{gro}}</td>
<td>
<button class="remove" ng-click="removeItem(gro)">×</button>
</td>
</tr>
</table>
</div>
</section>
</div>
</body>
var app = angular.module('myApp', []);
app.controller('GroceryController', function($scope){
$scope.groceries = ['Nails', 'Pipe', 'Wood'];
$scope.addItem = function() {
$scope.groceries.push($scope.newItem);
$scope.newItem = '';
}
$scope.removeItem = function(item) {
var idx = $scope.groceries.indexOf(item);
$scope.groceries.splice(idx.l);
}
});
I have a JSfiddle here but I can't actually get it to run in there. It runs just fine when I try to do it in the browser. Maybe you can get it to run and then you can figure out the problem. I'd really appreciate it! Thanks.
https://jsfiddle.net/bt08rbqt/
Upvotes: 0
Views: 153
Reputation: 380
There is an error in your splice method. Use it as below-
$scope.removeItem = function(item) {
$scope.groceries.splice($scope.groceries.indexOf(item),1);
}
Upvotes: 1