Angularjs wrong $index after orderBy Angularjs wrong $index after orderBy angularjs angularjs

Angularjs wrong $index after orderBy


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);}


I started to learn angular and faced similar trouble, and based on the answer of @pkozlowski-opensource, I solved it just with something like

<a>  <img src="img/delete.png" ng-click="removeItem(items.indexOf(item))">  {{items.indexOf(item)}}</a> 


I had the same problem and other answers in this topic are not suitable for my situation.

I've solved my problem with custom filter:

angular.module('utils', []).filter('index', function () {    return function (array, index) {        if (!index)            index = 'index';        for (var i = 0; i < array.length; ++i) {            array[i][index] = i;        }        return array;    };});

which can be used this way:

<tr ng-repeat="item in items | index | orderBy:'Store.storeName'">

and then in HTML you can use item.index instead of $index.

This method is suitable for the collections of objects.

Please, take into account that this custom filter should be the first one in the list of all filters applied (orderBy etc.) and it will add the additional property index (the name is customizable) into the each object of the collection.