Angular.js ng-repeat filter by property having one of multiple values (OR of values)

后端 未结 7 1510
一向
一向 2020-12-01 05:58

Is it possible to filter an array of objects, such that the value of property can be either of a few values (OR condition) without writing a custom filter

相关标签:
7条回答
  • 2020-12-01 06:21

    I found a more generic solution with the most angular-native solution I can think. Basically you can pass your own comparator to the default filterFilter function. Here's plunker as well.

    0 讨论(0)
  • 2020-12-01 06:25

    I thing ng-if should work:

    <div ng-repeat="product in products" ng-if="product.color === 'red' 
    || product.color === 'blue'">
    
    0 讨论(0)
  • 2020-12-01 06:31

    In HTML:

    <div ng-repeat="product in products | filter: colorFilter">

    In Angular:

    $scope.colorFilter = function (item) { 
      if (item.color === 'red' || item.color === 'blue') {
      return item;
     }
    };
    
    0 讨论(0)
  • 2020-12-01 06:32

    Here is a way to do it while passing in an extra argument:

    https://stackoverflow.com/a/17813797/4533488 (thanks to Denis Pshenov)

    <div ng-repeat="group in groups">
        <li ng-repeat="friend in friends | filter:weDontLike(group.enemy.name)">
            <span>{{friend.name}}</span>
        <li>
    </div>
    

    With the backend:

    $scope.weDontLike = function(name) {
        return function(friend) {
            return friend.name != name;
        }
    }
    

    .


    And yet another way with an in-template filter only:

    https://stackoverflow.com/a/12528093/4533488 (thanks to mikel)

    <div ng:app>
      <div ng-controller="HelloCntl">
        <ul>
           <li ng-repeat="friend in friends | filter:{name:'!Adam'}">
                <span>{{friend.name}}</span>
                <span>{{friend.phone}}</span>
            </li>
        </ul>
    </div>
    

    0 讨论(0)
  • 2020-12-01 06:33

    Best way to do this is to use a function:

    <div ng-repeat="product in products | filter: myFilter">
    
    $scope.myFilter = function (item) { 
        return item === 'red' || item === 'blue'; 
    };
    

    Alternatively, you can use ngHide or ngShow to dynamically show and hide elements based on a certain criteria.

    0 讨论(0)
  • 2020-12-01 06:37

    For me, it worked as given below:

    <div ng-repeat="product in products | filter: { color: 'red'||'blue' }">
    
    <div ng-repeat="product in products | filter: { color: 'red'} | filter: { color:'blue' }">
    
    0 讨论(0)
提交回复
热议问题