【问题标题】:AngularJS. Multiple conditions in Filter in ng-repeat角JS。 ng-repeat 中的过滤器中的多个条件
【发布时间】:2016-08-30 00:17:51
【问题描述】:

如果我将任何条件放在首位,为什么我的条件不起作用。

  1. 我在 PriceTo 中输入了 100 => 我得到了所有价格 > 100 的商品
  2. 我在名称中添加了“App” => 没有任何变化 但我应该在 (price > 100) AND (Name contains "App") 处获得商品。

小提琴: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

【问题讨论】:

  • 错误是什么?小提琴似乎工作正常
  • 如示例图像中所示。当我在 PriceTo 中输入 100 时,我得到所有价格 > 100 的项目,然后我在名称中输入“App”,没有任何变化。但我必须获得价格 > 100 且名称包含“App”的项目。

标签: javascript angularjs filter angularjs-ng-repeat angular-filters


【解决方案1】:

您的过滤功能有错误的条件。

尝试以下方法:

$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;
    };

这里是jsfiddle

【讨论】:

  • 我明白了...如果 $scope.something 存在,那么我们使用条件。对吗?
  • 1 已经存在于问题中,它没有做任何事情(因为 ASI 这变成了if(x) { 1; y(); })所以它可以被删除。
  • @ValSaven - 对,如果你在输入中放了一些东西,那么它才会使用这个条件,
  • @Caramiriel - 刚刚这样做了 :)
猜你喜欢
  • 2015-06-24
  • 2017-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多