Angularjs filter on two values of one field

94 Views Asked by At

I need to use either a filter or another, how to do?

<tr ng-repeat="currentCollectionItem in binding 
               | filter: ({ isPending: false } || {isPending: undefined})">
3

There are 3 best solutions below

0
Wictor Chaves On BEST ANSWER

Solution

You can do this using only one condition:

filter:'!true'

This is how you can apply false and undefined properties.

Example

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-filter-filter-production</title>
  <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
</head>
<body ng-app="">
<div ng-init="binding = [{name:'John', isPending:false},
                         {name:'Mary', isPending:false},
                         {name:'Mike', isPending:undefined},
                         {name:'Adam'},
                         {name:'Julie', isPending:true},
                         {name:'Juliette', isPending:true}]"></div>

<table id="searchTextResults">
  <tr><th>Name</th><th>isPending</th></tr>
  <tr ng-repeat="currentCollectionItem in binding | filter:'!true'">
    <td>{{ currentCollectionItem.name }}</td>
    <td ng-show="{{currentCollectionItem.isPending !== undefined}}">{{ currentCollectionItem.isPending }}</td>
    <td ng-show="{{currentCollectionItem.isPending === undefined}}">undefined</td>
  </tr>
</table>
</body>
</html>

4
GregL On

Your best bet is to define a filter method on your controller/component class and use that instead.

This has two main advantages:

  1. Easier to unit test - you can call the function on your controller/component instance directly to test the filter logic.
  2. Simpler markup/keeps the complicated code where it belongs, in the JS.

If you need help doing this, let me know.

1
georgeawg On

Use a custom predicate function:

<tr ng-repeat="currentCollectionItem in binding | filter: notPendingFilterFn">
$scope.notPendingFilterFn = function(value, index, array) {
     return value.isPending === false || value.isPending === undefined;
};

A predicate function can be used to write arbitrary filters. The function is called for each element of the array, with the element, its index, and the entire array itself as arguments.

For more information, see