使用数组通过单词进行过滤

时间:2017-08-27 05:04:54

标签: javascript angularjs

我目前有一个代码,允许我通过名称和标题过滤JSON对象。我有一个单词的数组,我想使用数组制作相同的过滤器。我不想使用输入文本,我需要使用数组。

我想按照数组中的每个单词进行过滤

$scope.arrayFilter=["is","mom","beautifull"];

enter image description here

启动应用程序时,默认情况下是否可以执行此过滤器?非常感谢你。

<li ng-repeat="item in data ">
 <span ng-bind-html="item.title | highlight:search"></span>
</li>

$scope.arrayFilter=["is","mom","beautifull"];
$scope.data = [{
    title: "mom is beautifull"
  }, {
    title: "my mom is great"
  }, {
    title: "I hate the matematics"
}];

.filter('highlight', function($sce) {
     return function(text, phrase) {
         if (phrase) text = text.replace(new RegExp('('+phrase+')', 'gi'),
            '<span class="highlighted">$1</span>')

          return $sce.trustAsHtml(text);
     }
 });

1 个答案:

答案 0 :(得分:1)

你需要将整个数组传递给你的过滤器并查看它是否在句子中,你需要在这里做一个小调整,把数组按正确的顺序排列以使句子匹配。否则,使用过滤器无法实现这一点。

version: '3'

services:

  dummy:
    image: xxx/xxx:latest
    restart: always
    environment:  
      - SPR_PROFILE=docker
      - CONFIG_SERVER_URL=http://configserver:8888/
    ports:
      - 8080:8080
    depends_on:
      - postgres
      - configserver
      - discovery

<强> $scope.arrayFilter=["mom","is","beautifull"];

DEMO
var app = angular.module('testApp',[]);
app.controller('testCtrl',function($scope){
$scope.arrayFilter=["mom","is","beautifull"];
$scope.data = [{
title: "mom is beautifull"
}, {
title: "my mom is great"
}, {
title: "I hate the matematics"
}];
});



app.filter('highlight', function($sce) {
return function(text, arrayFilter) {
    var stringToDisplay = '';
    angular.forEach(arrayFilter,function(key,value){
        if(text.includes(key)){
          stringToDisplay =  stringToDisplay.concat(key).concat(" ");
        }
    })
   stringToDisplay =  stringToDisplay.substring(0, stringToDisplay.length - 1);
   return $sce.trustAsHtml(text.replace(new RegExp(stringToDisplay, 'gi'), '<span class="highlightedText">$&</span>'));

}
});
.highlightedText {
    background: yellow;
}