Skip to content Skip to sidebar Skip to footer

Filtering ($filter) Matching Values From List Of Objects Excluding Unnecessary Properties

I'm trying to modify the behavior of Smart Table global search by defining my custom filter st-set-filter='myCustomFilter'. Here it is .filter('myCustomFilter', ['$filter', functio

Solution 1:

Just put that exclusion logic in your filter predicate. You can pass that predicate directly to the HTML via its function name.

A predicate function is a function that takes some parameters (typically an object) and returns a true or false value. This predicate will usually be evaluated individually on each element of an array. In the case of $filter, the predicate determines whether to include or exclude that element. This means you just need to write that function to properly include the right elements while excluding the wrong ones.

From the documentation for angular's $filter, the predicate has this signature:

function(value, index, array): 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.

You don't have to use all the inputs, and often you'll only need the first argument (the element itself). Your filtering predicate might look like this:

$scope.customFilter = function(item, index, array) {
  var excluded = item.testResult == 'fail';
  //.contains() logic for a search filter 
  var included = item.name.toLowerCase().indexOf($scope.filterData.name.toLowerCase()) > -1;

  return included && !excluded;
};

And then just pass the predicate function itself to your filter in the HTML:

<div ng-repeat="obj in data | filter:customFilter">
     Do stuff with the filtered data
</div>

I've linked a demo on plnkr that demonstrates the basic idea of how your predicate can interact with other parts of the form to include some elements while also excluding others.


Regarding the smart table. I'm not sure about what your smart table is expecting, but if is just wants a $filter object, then you should be able to leverage the predicate argument of the $filter. Just pass your predicate function (such as the one shown above) into your custom filter with filterName:arg1. I learned about this syntax from Todd Motto's page (section 3: filters for repeats with arguments).

Filter definition

//same as your filter, but named a bit better
.filter('appLevelFilter', ['$filter', function($filter){
    return function(input, predicate){
        return $filter('filter')(input, predicate, false);
    }
}])

HTML

<div ng-repeat="obj in data | appLevelFilter:customFilter">
     Do stuff with the filtered data
</div>

Post a Comment for "Filtering ($filter) Matching Values From List Of Objects Excluding Unnecessary Properties"