New solution: accessing filtered array outside ng-repeat

For developers who still use Angular 1.x just like me.

Frequently we may come across the situation that we filter some array and then want to use the filtered items in our controller, like the following:

// html
<div ng-repeat="book in filteredBooks = (books | customFilter:'xx')">
...
</div>
// controller
$scope.books = ['Ajax', 'Html', 'CSS']
$scope.filteredBooks ...

Unfortunately this usage will result in ‘undefined’ for the ‘filteredBooks’ variable, though it works for filtering the books. I googled a lot and tried several solutions like here, but still not worked and seemed like missing the point. Then I went back to Angular docs for ‘ngRepeat’ and finally noticed that:

Image for post
Image for post

Oh yeah, ngRepeat will create new scope, so variable ‘filteredBooks’ actually lives in the nested scope and not accessiable in our own controller even if we define the variable with the same name. So how to tackle this? Someone may suggest that we use $filter in our controller to avoid the template way, but here I just provide a new and simpler solution: explicitly bind the filtered variable to the parent scope! Remember that we have the great $parent attribute. Have a look.

// html
<div ng-repeat="book in $parent.filteredBooks = (books | customFilter:'xx')">
...
</div>

So in this way scope issues don’t exist anymore, you can always access ‘filteredBooks’ in your own controller and continue the happy coding. Have a try 😄

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store