ltalhouarne
ltalhouarne

Reputation: 4636

Index of ng-repeat without filter

I am looking for a native way of getting the index of an object from the full ng-repeat array instead of the filtered one.

Let's consider the following array:

{'1','2','3','4'} with respective indices of 0, 1, 2 and 3.

Let's also consider a custom filter which returns the following array:

{'1','3'} with respective indices of 0, 1.

Now the index of '3' in the filtered array is 1. However, what I am looking for is index 2 from the full array.

So, how can I obtain the index of an object from the full array instead of the filtered one? I would like to avoid having to look for the object in the full array on each applied filter.

Note: Objects don't and will not have ids.

Representative Fiddle

Upvotes: 0

Views: 227

Answers (2)

Kiran A
Kiran A

Reputation: 1

var app = angular.module('myapp', []);

app.controller('MainCtrl', function($scope) {
$scope.full = ['10','2','30','4'];
$scope.filter=['10','30']
});

template: <div ng-controller="MainCtrl">
<div ng-repeat="i in filter">
{{full.indexOf(i)}}
</div>
</div>

Upvotes: 0

JLRishe
JLRishe

Reputation: 101682

How about just using an initial step to include the indices:

angular.module('testApp', [])
.controller('test', ['$scope', function ($scope) {
    $scope.customFilter = function (data) {
        return data.val.no != '2' && data.val.no != '4';
    };

    $scope.withIndices = function (ary) {
        return ary.map(function (el, i) {
            return { i: i, val: el };
        });
    };
}]);
<ul ng-controller="test">
  <li ng-repeat="x in withIndices(names) | filter:customFilter">
  Item: {{ x.val.no }} index: {{x.i}} </li>
</ul>

Modified example

Upvotes: 1

Related Questions