angularjs - 如何过滤掉包含以下一个或多个单词的文本

标签 angularjs filter

如果我有一个对象数组

var obj = [{
  text: "Hello my name is none of your business"
  },
  { 
  text: "This is the second text of this object, hello"
  },
  { 
  text: "This is the third text of this object, hello"
  },{ 
  text: "This is a copy of the third text of this object, hello"
  }];

我怎样才能过滤掉所有包含不一定按顺序包含关键字的对象?提供了一个 jsfiddle 以进一步说明

例如

  • 用户搜索“this”,过滤器返回第二、第三和第四个文本

  • 用户搜索“第三个副本”,过滤器仅返回第四个文本,

问题是使用基本过滤器(下面的示例)似乎搜索的是准确的短语。例如“第三个副本”将返回一个空结果。用户必须输入“copy of the third”才能返回结果。

JSFiddle:http://jsfiddle.net/mpm2uamf/

我想在所有单个空格上使用 split 函数,然后使用 Regex 以某种方式循环...但我显然不知道我在做什么

.filter('searchBody', function(){
return function(elements, input){


  if(input !== undefined){
    var inputs = input.split(" ");

  }
  var filtered = [];
  // loop through user inputs and make them optional in RegExp?
  var letterMatch = new RegExp(inputs, 'i');
  for(var i = 0; i < elements.length; i++){
    var element = elements[i];
    if( letterMatch.test(element.body)){
      filtered.push(element);
    }
  }
  return filtered;
};
})

有人可以给我提示或解释如何做到这一点吗?

最佳答案

我创建了一个自定义过滤器来执行此操作:

app.filter('multipleTags', function($filter) {
  return function multipleTags(items, predicates) {
    predicates = predicates.split(',')

    angular.forEach(predicates, function(predicate) {
      items = $filter('filter')(items, predicate.trim())
    })
    return items;
  }
})

http://plnkr.co/edit/ZhnuM0WW3GZS5QLxK98t?p=preview

虽然我的代码是为逗号分隔的标签设计的,但它可以在您的情况下重复用于空格

关于angularjs - 如何过滤掉包含以下一个或多个单词的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28281351/

相关文章:

javascript - 如何在 AngularJS 中的不同 Controller 之间进行交互

javascript - 如何在功能上将各个时间戳聚合到时间范围中

python - Python 中的带通滤波器形状

excel - 是否可以使用公式或某种 AND OR 条件来过滤 Excel 表格?

javascript - 打开 Bootstrap 和 Angularjs 不工作的盒子

AngularJS ng-repeat with ng-change

node.js - Express.js - 过滤 URL 中的数字和字符串

AngularJS 更改日期格式(六月,星期三)从 Wed Jun 08 2016 05 :30:00 GMT+0530 (India Standard Time)

angularjs - AngularJS 适合 (3) 层架构吗?

javascript - 使用 ui.bootstrap 显示部分内容