简体   繁体   中英

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.

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.

If you don't mind doing all of the filtering and ordering in code, you can do everything inside your controller. Just make sure you inject $filter to it first.

// $filter must be injected earlier
$scope.filteredList = function(list) {
    var result;
    result = $filter('filter')(list, $scope.query);
    result = $filter('orderBy')(result, $scope.orderProperty);
    return result;
};

Then your HTML becomes

<div ng-repeat="stuff in filteredList(myList)">
    <label>{{$index}}</label> 
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM