Reputation: 999
Hello I am having problems of indexes when trying to delete from an array.
<i class="icon ion-ios-checkmark-outline" ng-click="addToHistory(task.info, task.measured, task.total, task.done, task.id)" ></i>
{{task.info}}
$scope.addToHistory = function(title, measured, total, done, id) {
var index = $scope.tasksCollection.indexOf($scope.tasksCollection[id]);
$scope.tasksCollection.splice(index, 1);
}
the Above works, but when I try to delete the first item, and go for the second one, the third gets deleted instead of the second one. I know is a problem of indexes, but I dont have ideas on how to solve it.
To recap I have:
when I delete the first one I get
and when I try to delete Item2, the index I get back is 1, so Item3 gets deleted.
Upvotes: 0
Views: 2385
Reputation: 111
This is a problem with using splice in a loop. Splice reindexes the array and makes length property obsolete. Generally the solution is to run through the array backwards when deleting. See this previous answer for more help.
Looping through array and removing items, without breaking for loop
Upvotes: -1
Reputation: 8055
$scope.tasksCollection[id]
Tries to get the task at index id - now depending on how that id is generated, you could either have something like :
$scope.tasksCollection[123] - which won't make sense (if it's an actual entity id)
or if you set the id property on the client side, once you remove from the collection, the ids won't match.
Use $index for what you want to do like HockeyJ suggested.
Upvotes: 1
Reputation: 16986
I think the issue is with using the task.id for the lookup.
Try passing in $index instead.
<i class="icon ion-ios-checkmark-outline" ng-click="addToHistory($index, task.info, task.measured, task.total, task.done, task.id)" ></i>
{{task.info}}
js
$scope.addToHistory = function(index, title, measured, total, done, id) {
$scope.tasksCollection.splice(index, 1);
}
Docs for index
Upvotes: 2