How can I obtain the result array of an angular “| filter” expression in a variable?

后端 未结 2 1342
灰色年华
灰色年华 2020-12-24 06:17

In angular, you can write filter expressions like



相关标签:
2条回答
  • 2020-12-24 06:24

    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.

    0 讨论(0)
  • 2020-12-24 06:36

    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.

    0 讨论(0)
提交回复
热议问题