Skip to content Skip to sidebar Skip to footer

AngularJs Filter With "or" Condition?

The code is available here: https://plnkr.co/edit/gbbsEnXxVpLsxvtKsDxw?p=preview. The filter filter: { a : 'x' } works and only one row is shown. Question: It seems filter: { a :

Solution 1:

As suggested by @Valery using custom Filter is the best solution around this.

Here is fork using custom filter(multiple conditions)

dashboard.component.js

.filter("optionalFilter",function(){
  //console.log("filter loads");
  return function(items, firstArgument,secondArgument){
    //console.log("item is ",items); // it is value upon which you have to filter
    //console.log("firstArgument is ",firstArgument);
    //console.log("secondArgument ",secondArgument);
    var filtered = [];
    angular.forEach(items, function(value, key) {
      //console.log("val ::",value);
      if(value.a == firstArgument || value.b == secondArgument){
       // console.log("val ::",value.a);
        this.push(value);
      }
    }, filtered);
    //console.log("val ::",filtered);
    return filtered;
  }

dashboard.component.html

   <tr ng-repeat="i in model.dashboardRows | optionalFilter:'aaa':2">

Useful references:


Solution 2:

Take a look at the filter filter docs, you can pass in an optional comparator parameter.

true: A shorthand for function(actual, expected) { return angular.equals(actual, expected)}. This is essentially strict comparison of expected and actual.

Note that this is case sensitive (as string comparsion is case sensitive in JS).

Also there is an example too at he bottom of the page that demonstrates filtering all or only a single property. If your filtering is complex, or your source data is big, filtering in controller can help readability and performance too.


Solution 3:

I think you should use custom filter

module.filter('myFilter', function(){
   return function(input){
      return input.filter(yourFilterFn);
   };
});

ng-repeat="item in items | myFilter"

Post a Comment for "AngularJs Filter With "or" Condition?"