【问题标题】:Custom angular search filter order by number of words matching按匹配字数的自定义角度搜索过滤器顺序
【发布时间】:2016-03-11 11:07:13
【问题描述】:

我想在 Angular JS 中创建一个预测文本自定义过滤器,它根据搜索查询过滤出字符串数组,并按与搜索查询中的单词匹配的单词数对它们进行排序。

过滤器应该返回相同的所有记录,即使搜索查询中单词的顺序与它们在记录数组中出现的顺序不匹配。(例如,如果我搜索“桌布”为一个搜索查询,它也应该能够匹配“餐桌装饰布”(请注意,角度过滤器不这样做))

还应该只允许搜索查询中单词的前缀匹配(例如,如果我有一个包含单词“phone”的记录,如果我在搜索查询中不应该显示的某个位置键入“one”)。

【问题讨论】:

  • 你能告诉我们你尝试了什么吗?
  • 我发布了答案。

标签: angularjs search angularjs-ng-repeat angularjs-filter


【解决方案1】:

我自己编写了一个自定义过滤器,它执行以下操作

  1. 仅前缀词匹配。

  2. 随机词索引匹配。

  3. 根据匹配的字数排序。

这是代码

HTML

            <ul>
                <li ng-repeat = "helpFAQ in helpCtrl.helpFAQs | filter: helpCtrl.filterBySearch | orderBy: ['-matchCount','priority'] | limitTo : helpCtrl.helpFaqLimit track by $index " ><a title="">{{helpFAQ.question}}</a></li>
                <li ng-if ="helpCtrl.showLessFaq"><a ng-click = "helpCtrl.showMoreFaq()" title="helpCtrl">[...]</a></li>
            </ul> 

AngularJS 自定义过滤器

 vm.helpFAQs = [{"question":"How can i hide an site?",
                 "priority":1},
                {"question":"How can i stop an ad?",
                "priority":7},
                {"question":"How do i change my email address?",
                "priority":9},
                {"question":"How do i pay electricity bill?",
                "priority":3},
                {"question":"How do i see the number of times I logged in?",
                "priority":6},
                {"question":"How do i set up a new connection?",
                "priority":3},
                {"question":"Where can i see disclosures for my account?",
                "priority":1},
                {"question":"Where can i see my privacy setting?",
                "priority":4},
                {"question":"Why can't i see my profile?",
                "priority":2}
                ];
vm.serchBoxKeyed = function(searchTerm){
     vm.regex = new RegExp('\\b' + vm.escapeRegExp(searchTerm), 'i');
}

vm.filterBySearch = function(topic) {
    topic.matchCount = 0;
    var searchTextSplit = vm.searchQuery.toLowerCase().split(' ');
      for(var y = 0; y < searchTextSplit.length; y++){
        vm.serchBoxKeyed(searchTextSplit[y]);
        var prefixMatch =vm.regex.test(topic.question);
        if(topic.question.toLowerCase().indexOf(searchTextSplit[y]) !== -1 && prefixMatch){
          topic.matchCount = topic.matchCount + 1;
        }
      }     
      if(topic.matchCount>0)
        return true;
      else
        return false;
};


vm.escapeRegExp = function(searchTerm){
  return searchTerm.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    • 2019-01-14
    • 2017-10-14
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多