使用多个条件进行逻辑与运算的 Angular JS 过滤器

4

我有一个文本框在我的HTML页面上,我希望通过逻辑与运算符过滤我输入框中的结果并显示在页面上。让我来演示一下。

假设在我的页面上,我有:

- Example number 1
- Example number 2
- Example number 3

通常,如果我想筛选结果,我会做类似以下的操作:
<input type= "text" ng-model= "query">

之后
<tr ng-repeat= "thing in blah | filter : query">
    <td> {{thing}} </td>
</tr>

所以,如果我输入了:
"Example"

我理解您不想进行过滤。但是,如何使用多个搜索词进行逻辑与运算呢?例如,如果我输入

"Example 1"

我应该只返回第一个例子,因为它包含“Example”和“1”。我在angular文档中没有看到任何可以让我这样做的东西,但我相信可以通过创建自己的过滤器来实现,我只是没有这样做的经验。

3个回答

4
创建自定义过滤器:
filter('and', function($log) {
  return function(items, query) {
    if (!query) return items; // return all items if nothing in query box

    var terms = query.split(' '); //split query terms by space character
    var arrayToReturn = [];

    items.forEach(function(item){ // iterate through array of items
      var passTest = true;
      terms.forEach(function(term){ // iterate through terms found in query box
        // if any terms aren't found, passTest is set to and remains false
        passTest = passTest && (item.toLowerCase().indexOf(term.toLowerCase()) > -1); 
      });
      // Add item to return array only if passTest is true -- all search terms were found in item
      if (passTest) { arrayToReturn.push(item); }
    });

    return arrayToReturn;
  }
})

使用它代替 filter: query

<tr ng-repeat="thing in blah | and:query">

Plunker Demo


顺便说一句,如果使用Underscore、lodash或者你愿意让这个程序在IE用户版本小于9的情况下出现问题,那么过滤器的内部代码可以进行一些清理。 - Marc Kline
如果我的“东西”不是一个文本字符串,而是一个具有名为“name”的字段的JavaScript对象。我该如何根据名称进行过滤? - Zack

2

我的解决方案。它利用了Angular的filterFilter,并且比所选答案具有以下3个优点:

  • 它还可以搜索对象(不仅仅是字符串)
  • 在搜索项之间可以是任何数量和类型的空格
  • 代码行数更少

这是代码:

  app.filter('multiple', ['filterFilter', function (filterFilter) {
    return function (items, query) {
      if (!query) return items;

      var terms = query.split(/\s+/);
      var result = items;
      terms.forEach(function (term) {
        result = filterFilter(result,term);
      });

      return result;
    }
  }]);

0

Marc 的被接受的答案也帮了我,但是如果使用对象而不是字符串,你需要使用点符号来访问特定的值。(例如 'name' 和 'title')

items.forEach(function(item){ // iterate through array of items
    var passTest = true;
    var found = false;
    terms.forEach(function(term){ // iterate through terms found in query box
        // if any terms aren't found, passTest is set to and remains false
        found = (item.name.toLowerCase().indexOf(term.toLowerCase()) > -1)
            || (item.title.toLowerCase().indexOf(term.toLowerCase()) > -1); 
        passTest = passTest && found;
    });
    // Add item to return array only if passTest is true -- all search terms were found in item
    if (passTest) { arrayToReturn.push(item); }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接