Search code examples
javascriptangularjsangularjs-scopeangularjs-ng-repeat

AngularJS - Getting filtered ng-repeat $index from inside a controller


I have an ng-repeat list with a filter. I can't seem to find how to get the visible $index from inside of my controller.

I can easily display it and it changes dynamically when the list is getting filtered.

<div ng-repeat="stuff in myList| filter:query | orderBy:orderProperty">
    <label>{{$index}}</label>
</div>

But I can't seem to get the correct $index programatically from within my controller. I've tried $scope.myList.indexOf(myObj) and a for loop, but I still don't get the right $index, I get the $index of the item in the original, unfiltered, list.

The reason I need this is because I have a global audio player and I need to autoplay the filtered list. So when my audio 'ended' I fire off to play the next() element in the visible list.


Solution

  • One way to solve this issue is to write your own custom filter and before returning the array, add an index to every element then use that index instead of $index.

    Here is some sample code.

    angular.module('myFilters', []).filter('filterWithIndex', function() {
      return function(input) {
        var filteredInput = [];
    
        for(var i = 0; i < input.length; i ++) {
          filteredInput.push(input[i]);
          filteredInput[i].index = i + 1;
        }
    
        return filteredInput;
      };
    });
    

    Hope this helps.