2

I want to filter out all objects with quantity less than 1 and I had to make a custom filter in order to achieve that. I was hoping that there was a simpler solution to the problem than a custom filter.

The following will not work:

<tr ng-repeat="product in products | filter: {quantity: '!0'}">

This will filter out 10,20 and so on in addition to 0.

I ended up using this custom filter:

app.filter('quantityFilter', function() {
  return function( products) {
    var filtered = [];
    angular.forEach(products, function(product) {
        if(product.quantity > 0 ){
            filtered.push(product);
        }
    });
    return filtered;
  };
});

HTML:

<tr ng-repeat="product in products | quantityFilter">

Is there a smoother solution to this? Like (does not work):

<tr ng-repeat="product in products | filter: {quantity: >0}">
PoengAlex
  • 153
  • 1
  • 7
  • 2
    Possible duplicate of [AngularJS : ng-repeat filter when value is greater than](http://stackoverflow.com/questions/24081004/angularjs-ng-repeat-filter-when-value-is-greater-than) – Azad Sep 22 '16 at 08:44

1 Answers1

2

Instead of writing a separate filter you can use a predicate function for the filter. This is described in detail in the AngularJS documentation.

so for you this becomes:

<tr ng-repeat="product in products | filter:noZeroQuantity">

and in the controller:

$scope.noZeroQuantity = function(value, index, array) {
    return value.quantity !== 0;
}

I wrote an example in jsfiddle.

Giovani Vercauteren
  • 1,898
  • 13
  • 22