Danielle Rodrigues
Danielle Rodrigues

Reputation: 61

Angularjs filter on two values of one field

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

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

Upvotes: 0

Views: 94

Answers (3)

Wictor Chaves
Wictor Chaves

Reputation: 1129

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>

Upvotes: 2

georgeawg
georgeawg

Reputation: 48968

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

Upvotes: 2

GregL
GregL

Reputation: 38103

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.

Upvotes: 1

Related Questions