Search code examples
javascriptangularjsfilterangularjs-ng-repeatangular-filters

AngularJS. Multiple conditions in Filter in ng-repeat


Why my condition doesn't work if I put the first of any condition.

  1. I put 100 in the PriceTo => I get all items, where price > 100
  2. I put "App" in the Name => nothing changes But I should get items where (price > 100) AND (Name contains "App").

fiddle: http://jsfiddle.net/QHtD8/142/

JS:

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
    $scope.products = [
        {name:"Apple",type:"fruit",price:100},
        {name:"Grape",type:"fruit",price:500},
        {name:"Orage",type:"fruit",price:555},
        {name:"Carrot",type:"vegetable",price:1000},
        {name:"Milk",type:"dairy",price:800}
    ];

    $scope.productFilter = function (item) {1
        var result = item.name === $scope.foodName ||
                             item.price >= $scope.priceFrom ||
                   item.price <= $scope.priceTo;
            return result;
        };

}

HTML:

    <div ng-controller="MyCtrl">
    Name
    <input ng-model="foodName" /><br>
    Price from
    <input ng-model="priceFrom" /><br>
    Price to
    <input ng-model="priceTo" /><br>
    <ul>
        <li ng-repeat="item in products | filter:productFilter">
          {{item.name}} - {{item.price}}
        </li>
    </ul>
</div>

Example


Solution

  • You have a wrong conditions in your filtration function.

    Try the following:

    $scope.productFilter = function (item) {
            var result = (!$scope.foodName || item.name.toLowerCase().includes($scope.foodName.toLowerCase())) && 
                         (!$scope.priceFrom || item.price >= $scope.priceFrom) &&
                         (!$scope.priceTo || item.price <= $scope.priceTo);
    
            return result;
        };
    

    Here is jsfiddle