【问题标题】:Custom filter works initially, but not after a Search is performed自定义过滤器最初有效,但在执行搜索后无效
【发布时间】:2016-06-02 13:57:29
【问题描述】:

我正在尝试解决自定义过滤器的问题。我已经配置了jsFiddle to replicate the issue

Out of Stock 过滤器是具有奇怪行为的自定义过滤器。最初它工作正常。但是,如果您在搜索框中输入文本,请从搜索框中删除文本,然后再次尝试使用“缺货”过滤器,它不会返回任何结果。

我被难住了。我认为这可能与过滤器逻辑在控制器中的工作方式有关,但我不明白为什么在将文本输入搜索后它没有读取项目数量值。

这是“缺货”过滤器的自定义过滤器逻辑:

  $scope.changeStockFilter = function() { // this function call on change checkbox value
    if ($scope.searchInventory.qty === 0) {
      $scope.exactMatching = true; // if qty 0 then set true
    } else {
      $scope.exactMatching = false;
    }
  };

下面是过滤器函数的调用方式

        <div class="checkbox">
            <input type="checkbox" name="filter" ng-model="searchInventory.inventory" data-ng-true-value="0" data-ng-false-value="''" ng-change="changeStockFilter()">
            Out of Stock
        </div>

这就是将过滤器应用于 ngrepeat 的方式

<div ng-repeat="item in inventory | filter: searchInventory : exactMatching | orderBy:sortOrder as filtered_result track by $index">

我还认为过滤器中的“track by”可能存在问题,假设我使用不正确。我阅读了下面链接的几页,我认为这不是问题所在。当然,我可能是错的。

我希望能提供有关此问题的任何指导。谢谢!!!

【问题讨论】:

  • 除非您通过单击“x”(仅限 IE)清除搜索输入,否则它似乎可以正常工作。对吗?

标签: javascript angularjs filter


【解决方案1】:

使用search 后,您的过滤器对象如下所示:

{ "qty": 0, "$": "" }

exactMatching = true 一起,这不会返回任何结果,因为 Angular 在这种情况下使用严格比较 (angular.equals(actual, expected)) 而不是不区分大小写的子字符串匹配,并且由于这部分 "$": "" (这意味着应该是至少一个属性等于空字符串)。

您应该对 outOfStock 事物使用单独的过滤器,并进行严格比较。其他过滤器应使用substring match in case insensitive way

<div ng-repeat="item in inventory | filter: searchInventory | filter : outOfStockFilter | orderBy:sortOrder as filtered_result track by $index">

过滤功能:

$scope.outOfStockFilter = function(value, index, array) {
    return $scope.searchQty != 0 || value.qty === 0;
};

这里是工作分叉:http://jsfiddle.net/f417v1nn/

【讨论】:

  • @MattG., "$": "" 来自 search 字段。如果您在搜索字段中输入“Bee”,它将是"$":"Bee",这意味着搜索“Bee”的所有属性。当您清空搜索字段时,它会显示"$":"",它会在所有属性中搜索一个空字符串,该字符串在完全匹配模式下找不到任何内容(当 outOfStock 处于打开状态时)。在您使用搜索字段之前,angular 不会将该属性 "$":"" 添加到 inventorySearch 对象中,这就是搜索工作正常的原因。
  • 明白了!这对我来说真的很清楚。非常感谢!
猜你喜欢
  • 2021-06-07
  • 1970-01-01
  • 1970-01-01
  • 2018-03-15
  • 1970-01-01
  • 1970-01-01
  • 2013-04-25
  • 1970-01-01
  • 2010-09-23
相关资源
最近更新 更多