【问题标题】:Conditional filter for checking all keys in array of objects using multiple inputs使用多个输入检查对象数组中所有键的条件过滤器
【发布时间】:2019-02-20 14:10:28
【问题描述】:

我有一个对象数组:

scope.values = [
   {'key1':'valueA', 'key2': 'valueD'},
   {'key1':'valueB'},
   {'key1':'valueC'}
]

我想过滤一个搜索输入,它可以包含多个用逗号或空格分隔的单词:

<input ng-model="scope.search"></input>

我们可以这样列出数组:

<p ng-repeat="index, obj in scope.values | filter:scope.search"></p>

但是,这仅适用于一个输入。当我有多个输入时我能做什么,例如约翰·多伊。

请注意,我希望它是有条件的。所以不是在找到 John 或 Doe 时,而是在找到 John 和 Doe 时。

【问题讨论】:

  • 在 99% 的关于 angularjs 过滤器的问题中,答案非常简单:不要使用过滤器——在控制器中进行过滤以提高性能和可测试性
  • 上述场景仅适用于“OR”条件,对于“AND”条件,您可以实现自己的自定义过滤器。
  • 在控制器中过滤?

标签: angularjs angularjs-filter


【解决方案1】:

我不认为内置过滤器可以做到这一点。您可能想要的是一个自定义过滤器,如文档here(大约在页面下方)和官方教程here 中所述。

例如,这个自定义过滤器应该做你想做的。

app.filter("multiSearch", [
   function() {
      //"data" is your searchable array, and "search" is the user's search string.
      return function(data, search) {
         //Get an array of search values by splitting the string on commas and spaces.
         var searchArray = search.toLowerCase().split(/[, ]/);
         //Use javascript's native Array.filter to decide which elements to cut and to keep.
         return data.filter(function(item) {
            //If the item contains ALL of the search words, keep it.
            var foundCount = 0;
            for (var searchElement of searchArray) {
               for (var attribute in item) {
                  if (
                     String(item[attribute])
                        .toLowerCase()
                        .includes(searchElement)
                  ) {
                     foundCount++;
                     break;
                  }
               }
            }
            if (foundCount === searchArray.length) {
               //Matched all search terms. Keep it.
               return true;
            }
            else {
               //Not a match. Cut it from the result.
               return false;
            }
         });
      };
   }
]);

然后在你的html中你可以这样称呼它:

<p ng-repeat="index, obj in scope.values | multiSearch:scope.search"></p>

如 cmets 中所建议的,您可能会考虑的另一件事是完全放弃使用过滤器,而只在控制器内部运行逻辑。您可以使用上面示例过滤器中提供的许多逻辑——您只需实现自己的系统即可在搜索查询更改时运行过滤逻辑。避免在 angularjs 中使用过滤器有好处,但这是另一个话题。

【讨论】:

    猜你喜欢
    • 2021-07-05
    • 2021-12-10
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    • 1970-01-01
    相关资源
    最近更新 更多