0

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

2
  • what is the error? fiddle seems to work fine Commented May 4, 2016 at 13:52
  • Like in the example image. When I put 100 in the PriceTo I get all items, where price > 100, then I put "App" in the Name and nothing changing. But I have to get items where price > 100 AND where Name contains "App". Commented May 4, 2016 at 13:53

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

I see... IF $scope.something EXISTS, then we use the condition. Right?
1 is already there in the question, it doesn't do anything (because of ASI this becomes if(x) { 1; y(); }) so it can be removed.
@ValSaven - right, if you put something in the inputs, only then it will use this condition,
@Caramiriel - just did this :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.