New solution: accessing filtered array outside ng-repeat

Jing
2 min readOct 25, 2017

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:

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 😄

--

--

Jing

Breathtaking interfaces and strong services together make great products