Filtered arrays outside ng-repeat loops

Ng-repeats are great, it’s very easy to filter through a collection:

But, as you type a query in the filter, notice that the number of the collection ‘friends’ remains 4 no matter how many friends are currently shown in the ng-repeat after $filter has done its job: Screen Shot 2015-07-23 at 2.16.26 PM So, how can you access friends  after it has been filtered? There might be cases when you need to know the amount of filtered elements, or you need to access the filtered collection outside the ng-repeat loop. Well, the solution is really easy and shows how AngularJS can do amazing thing with declarative syntax:

With only doing that we’re creating a new variable in our scope called  friendsAfterFilter. You can access $scope.friendsAfterFilter  in any other part of your application controllers, watchers, etc. Just remember the $scope  will be the same as your original collection:


Having a new collection in the scope and the variable assignment  friend in friendsAfterFilter = (friends | filter:search) means  friendsAfterFilter  will be re-evaluated in every $digest cycle. Please consider this impact when building your application.

  • Martin

    nice man, just remember YU is the name!

  • James Wyse

    If you’re using Angular >= 1.3 try this, you should see much better performance:

    ng-repeat=”friend in friends | filter:search as friendsAfterFilter track by”

  • odiseo42

    Hello James,
    ‘track by’ has been since 1.2 and even before. Would you care to elaborate why this brings a performance boost?