突出显示数组中的单词

yav*_*avg 4 javascript arrays angularjs

我想在数组中标记我的单词.

$scope.arrayFilter=["mom","is","beautifull"];
Run Code Online (Sandbox Code Playgroud)

但它只适用于我,如果我按照它们出现的顺序排列的话.我希望无论这些单词的顺序如何,如果它们匹配,都会标记.如果我向数组添加一个新单词,它也应该被标记.

https://jsfiddle.net/1x7zy4La/

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

  $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>'));

}
});
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

kuk*_*kuz 5

问题是你是concating你的钥匙 -改变你的filter这个:

app.filter('highlight', function($sce) {
  return function(text, arrayFilter) {
    angular.forEach(arrayFilter, function(key, value) {
      if (text.includes(key)) {
        text = text.replace(new RegExp(key, 'gi'), '<span class="highlightedText">$&</span>')
      }
    })
    return $sce.trustAsHtml(text);
  }
});
Run Code Online (Sandbox Code Playgroud)

请参阅updated jsfiddle或演示如下:

var app = angular.module('testApp', []);
app.controller('testCtrl', function($scope) {
  $scope.arrayFilter = ["is", "mom", "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) {
    angular.forEach(arrayFilter, function(key, value) {
      if (text.includes(key)) {
        text = text.replace(new RegExp(key, 'gi'), '<span class="highlightedText">$&</span>')
      }
    })
    return $sce.trustAsHtml(text);
  }
});
Run Code Online (Sandbox Code Playgroud)
.highlightedText {
  background: yellow;
}
Run Code Online (Sandbox Code Playgroud)
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>

<div ng-app="testApp" ng-controller="testCtrl">
  <li ng-repeat="item in data ">
    <span ng-bind-html="item.title | highlight:arrayFilter"></span>
  </li>
</div>
Run Code Online (Sandbox Code Playgroud)