35

In angular, you can write filter expressions like

<input type="text" ng-model="query"> <table> <tr ng-repeat="phone in phones | filter: query"> <td>{{phone.vendor}}</td> <td>{{phone.model}}</td> </tr> </table> 

and it will update the table to show only the phones which match the query text you enter into the input.

How can I get the corresponding result array of the filter, e.g. the [phone object]s that are currently displayed, in a variable (e.g. a scope variable)?

1

2 Answers 2

80

You can actually assign new variables to the scope in an angular expression. So the simplest solution would be to do <tr ng-repeat="phone in (filteredPhones = (phones | filter: query))">. filteredPhones is now a variable in the current scope - see this plnkr example.

Sign up to request clarification or add additional context in comments.

4 Comments

This is great, and so simple!
Is it possible to get somehow the event on query changes?
You could do $scope.$watch('query',function(newQuery,oldQuery){ ... });
this doesn't work for me - the filteredVariable is always undefined on my $scope. does this require a specific version of angular?
19

Inside your controller, you can watch changes to your query text and use the Javascript equivalent of {expression} | filter: {expression}, which is $filter('filter') (using the filter named 'filter' from the service $filter, which you have to inject).

Let's say your HTML snippet is controlled by the controller MyController. Then you can change it to:

myApp.controller("MyController", ["$scope", "$filter", function($scope, $filter) { $scope.$watch('query', function(newVal, oldVal) { console.log("new value in filter box:", newVal); // this is the JS equivalent of "phones | filter: newVal" $scope.filteredArray = $filter('filter')($scope.phones, newVal); }); }]); 

Whenever your query changes, the filtered array will be available as filteredArray in your $scope, and you can use filteredArray as an expression in your snippet.


All this should actually be documented in http://docs.angularjs.org/api/ng.$filter and http://docs.angularjs.org/api/ng.filter:filter. However, the documentation of the first link is way too sparse you can really only get it from the comments to the second link. I tried to add it to the docs, but after cloning angular and building the docs, accessing them via the browser simply did not work and navigating the API failed silently without any useful error, so I gave up on that.

1 Comment

Watching filteredPhones in @joakimbl's example did not seem to be a good solution (too many events) so if you want to add some logic after the filter is applied, this version is preferable, I think.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.