I am new to Angular.js and have some problems sorting my array and working on that sorted data.
I have a list with items and want so sort it by "Store.storeName", which is working so far. But after sorting the data, my delete-function is not working anymore. I think thats because the $index is wrong after sorting, and so the wrong data is deleted.
How can I solve that? Ordering the data in the scope and not in the view? How to do that?
Here is some relevant code:
In the View:
<tr ng-repeat="item in items | orderBy:'Store.storeName'">
<td><input class="toggle" type="checkbox" ng-model="item.Completed"></td>
<td>{{item.Name}}</td>
<td>{{item.Quantity}} Stk.</td>
<td>{{item.Price || 0 | number:2}} €</td>
<td>{{item.Quantity*item.Price|| 0 | number:2}} €</td>
<td>{{item.Store.storeName}}</td>
<td><a><img src="img/delete.png" ng-click="removeItem($index)">{{$index}}</a></td>
</tr>
And in my controller I have this delete function, which should delete the specific data:
$scope.removeItem = function(index){
$scope.items.splice(index,1);
}
This works nicely before ordering in the View. If something important is missing, please let me now.
Thanks!
Instead or relaying on the $index
- which - as you have noticed - will point to the index in a sorted / filtered array, you can pass the item itself to your removeItem
function:
<a><img src="img/delete.png" ng-click="removeItem(item)">{{$index}}</a>
and modify the removeItem
function to find an index using the indexOf
method of an array as follows:
$scope.removeItem = function(item){
$scope.items.splice($scope.items.indexOf(item),1);
}