How to filter multiple values (OR operation) in angularJS

前端 未结 20 889
清酒与你
清酒与你 2020-11-22 10:01

I want to use the filter in angular and want to filter for multiple values, if it has either one of the values then it should be displayed.

I have for

相关标签:
20条回答
  • 2020-11-22 10:30

    the best answer is :

    filter:({genres: 'Action', genres: 'Comedy'}
    
    0 讨论(0)
  • 2020-11-22 10:32

    I had similar situation. Writing custom filter worked for me. Hope this helps!

    JS:

    App.filter('searchMovies', function() {
        return function (items, letter) {
            var resulsts = [];
            var itemMatch = new RegExp(letter, 'i');
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                if ( itemMatch.test(item.name) || itemMatch.test(item.genre)) {
                    results.push(item);
                }
            }
            return results;
        };
    });
    

    HTML:

    <div ng-controller="MoviesCtrl">
        <ul>
            <li ng-repeat="movie in movies | searchMovies:filterByGenres">
                {{ movie.name }} {{ movie.genre }}
            </li>
        </ul>
    </div>
    
    0 讨论(0)
  • 2020-11-22 10:33

    Too late to join the party but may be it can help someone:

    We can do it in two step, first filter by first property and then concatenate by second filter:

    $scope.filterd = $filter('filter')($scope.empList, { dept: "account" });
    $scope.filterd = $scope.filterd.concat($filter('filter')($scope.empList, { dept: "sales" }));  
    

    See the working fiddle with multiple property filter

    0 讨论(0)
  • 2020-11-22 10:33

    OPTION 1: Using Angular providered filter comparator parameter

    // declaring a comparator method
    $scope.filterBy = function(actual, expected) {
        return _.contains(expected, actual); // uses underscore library contains method
    };
    
    var employees = [{name: 'a'}, {name: 'b'}, {name: 'c'}, {name: 'd'}];
    
    // filter employees with name matching with either 'a' or 'c'
    var filteredEmployees = $filter('filter')(employees, {name: ['a','c']}, $scope.filterBy);
    

    OPTION 2: Using Angular providered filter negation

    var employees = [{name: 'a'}, {name: 'b'}, {name: 'c'}, {name: 'd'}];
    
    // filter employees with name matching with either 'a' or 'c'
    var filteredEmployees = $filter('filter')($filter('filter')(employees, {name: '!d'}), {name: '!b'});
    
    0 讨论(0)
  • 2020-11-22 10:34

    I believe this is what you're looking for:

    <div>{{ (collection | fitler1:args) + (collection | filter2:args) }}</div>
    
    0 讨论(0)
  • 2020-11-22 10:36

    My solution

    ng-repeat="movie in movies | filter: {'Action'} + filter: {'Comedy}"
    
    0 讨论(0)
提交回复
热议问题