【问题标题】:AngularJS filtering - multiple expressions or dynamically chain ng-filters?AngularJS 过滤 - 多个表达式或动态链接 ng 过滤器?
【发布时间】:2014-04-12 02:28:00
【问题描述】:

如果您查看下面的代码,我想使用文本 <input> 来按多种成分过滤每个菜单项 - 例如,如果用户在 <input> 中输入“牛肉,培根” ,该应用将返回所有以牛肉或培根为原料的菜单项。

我目前正在尝试使用 ng-filter 执行此操作,我猜我需要为此创建一个自定义过滤器。这是错误的方法吗?有没有办法动态链接过滤器?

这里有一些代码应该可以理解我的问题 -

我的搜索模型: - 注意:使用 ng-list 将字符串转为子字符串数组

<div ng-init="searchString=[]">
    <input type="text" ng-model="searchString" ng-list>
</div>

我的 ng-repeat 循环: - 注意:使用自定义过滤器将我的每种成分加入一个字符串

<tr ng-repeat="item in menu | filter:{ category : 'Classics' } | filter:{ ingredients : searchString } ">
    <td class="title">{{ item.title }}</td>
    <td class="ingredients">
        {{ item.ingredients | join:', ' }}
    </td>
    <td class="price">{{ item.price | currency }}</td>
</tr>

我的数据结构

$scope.menu = [
    {
        "title" : "New Yorker",
        "price" : "4.00",
        "ingredients" : [
            "Salt Beef",
            "Pickles",
            "Mustard"
        ],
        "category" : "Classics"
    },
    {
        "title" : "BLT",
        "price" : "4.00",
        "ingredients" : [
            "Bacon",
            "Lettuce",
            "Tomato"
        ],
        "category" : "Classics"
    }
]

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    (我知道这可能是一个死问题,但我也发现了:)

    需要自定义过滤器,因为您要过滤与搜索列表共享至少一种成分的菜单项(即非空数组交集)。问题中使用的过滤器filter:{ ingredients : searchString } 不会以这种方式过滤,Angular 中内置的任何其他过滤器也不会从official doc 进行过滤。

    创建自定义过滤器很容易;在$scope中添加新函数containsIngredientsFromSearch

     // Filter functions are called separately for each item on the menu
    $scope.containsIngredientsFromSearch = function(menuItem){     
      // Check every ingredient on the search list ...
      for(var i in $scope.searchString) {
        var ingredient = $scope.searchString[i];
        // ... does it match an ingredient in menuItem.ingredients?
        if(menuItem.ingredients.indexOf(ingredient) !== -1) {
          // ... if so, stop searching and return true to include this menuItem
          return true;
        }
      }
    
      // No matching ingredient found? Return false to exclude this item.
      return false;
    }
    

    将过滤器添加到现有过滤器链中:

    &lt;tr ng-repeat="item in menu | filter:{ category : 'Classics' } | filter:containsIngredientsFromSearch"&gt;

    看到它在行动on JSBin

    【讨论】:

      【解决方案2】:

      您可以创建自定义过滤器,或使用带有谓词(函数)的角度过滤器

      { filter_expression | filter:predicateFunction }}
      

      当然,您的函数位于控制器的范围内,搜索字符串可见

      谓词函数可用于编写任意过滤器。这 为数组的每个元素调用函数。最终结果是一个 谓词返回 true 的那些元素的数组。

      http://docs.angularjs.org/api/ng.filter:filter

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-02
        • 1970-01-01
        • 2016-06-16
        • 1970-01-01
        • 2013-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多