Rich
Rich

Reputation: 6573

angularjs - counting in reverse in ng-repeat with filtering

I have an array of 115 books stored in details below in ng-repeat. When using {{$index +1}} a count of 1 to 115 appears. If I filter the books by last name and show 12, {{$index + 1}} will show a count of 1 to 12. Is it possible to instead show a reverse count using $index so that the count starts with the highest number and goes to lowest? Without filtering, this will work using {{details.length - $index}} but when filtering the results in 12 items show 115 through 104 instead of 12 through 1.

I have an ng-repeat like this:

<tr ng-repeat="det in details | orderBy:['-YEAR_READ','-UniqueCounter'] | filter:searchingFor>
    <td>{{$index + 1}}</td>
    <td>{{details.length - $index}}</td>
    <td>

Upvotes: 3

Views: 435

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136194

Currently while showing the index you are referring the unfiltered collection, therefore you can't see the filtered result count using details.length variable. Use alias filter object using as would do the trick like ng-repeat="item in item | filter: { prop: 'search' }| customFilter as filteredResult"

<tr 
  ng-repeat="det in details | orderBy:['-YEAR_READ','-UniqueCounter'] | filter:searchingFor as filtered">
    <td>{{$index + 1}}</td>
    <td>{{filtered.length - $index}}</td>
    <td>
</tr>

Upvotes: 2

Yoan
Yoan

Reputation: 2207

You can apply to the collection a new filter to get the reverse behavior, like:

app.filter('reverse', function() {
  return function(items) {
    return items.slice().reverse();
  };
});

and use it like:

<tr ng-repeat="det in details |reverse | orderBy:['-YEAR_READ','-UniqueCounter'] | filter:searchingFor >
    <td>{{$index + 1}}</td>
    <td>{{details.length - $index}}</td>
    <td>
</tr>

Upvotes: 0

Related Questions