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)?

nh2
  • 24,526
  • 11
  • 79
  • 128
  • 2
    Possible duplicate of [AngularJS - how to get an ngRepeat filtered result reference](https://stackoverflow.com/questions/11721863/angularjs-how-to-get-an-ngrepeat-filtered-result-reference) – Damjan Pavlica Nov 25 '17 at 22:11

2 Answers2

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.

joakimbl
  • 18,081
  • 5
  • 54
  • 53
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.

nh2
  • 24,526
  • 11
  • 79
  • 128
  • 4
    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. – aweibell Sep 03 '13 at 15:42