使用AngularJS过滤器突出显示多个单词

时间:2017-02-21 00:57:21

标签: angularjs

我正在使用AngularJS,目前我只设法在文本中突出显示单个单词。但我想用不同颜色突出显示多个单词。

使用网络电话的响应:

{
    "text" : "This is a long wall of text of which contains multiple words that I want to highlight using multiple colors",
    "word1" : "wall",
    "word2" : "words",
    "word3" : "colors"
}

我想显示如下文字:

results

2 个答案:

答案 0 :(得分:2)

这是做熊工作的另一种方式fiddle

function myCtrl($scope) {
$scope.item = {
text: "I am a Bear in the forest. We are two bears climbing a tree.",
search: [{
  text: "Bear",
  color: "brown"
}, {
  text: "forest",
  color: "green"
}, {
  text: "tree",
  color: "orange"
}]
};
}

var app = angular.module('myApp', ['highlightDirective']);
app.controller('myCtrl', ['$scope', myCtrl]);

function highlight() {

var directive = {
restrict: 'E',
scope: {
  text: '=',
  search: '='
},
link: function link(scope, $element, attr) {

var text = scope.text;
var search = scope.search;

for (var i = 0; i < search.length; i++) {
  var s = search[i];
  var html = '<span class="highlightText ' + s.color + '">$&</span>';

  text = text.replace(new RegExp("\\b" + s.text + "\\b"), html);
}

    $element.html(text);
    }
  };
  return directive;
}

var highlightDirectiveModule = angular.module("highlightDirective", []);
highlightDirectiveModule.directive('highlight', highlight);

答案 1 :(得分:1)

这是保持数据结构的一种方法。

angular.module('myApp', [])
  .controller('myCtrl', function($scope) {
    $scope.response = {
      "text": "This is a long wall of text of which contains multiple words that I want to highlight using multiple colors",
      "word1": "wall",
      "word2": "words",
      "word3": "colors"
    };
  })
  .directive('highlight', function() {
    return {
      restrict: 'E',
      scope: {
        data: '='
      },
      link: function(scope, element, attrs) {
        let text = scope.data.text;
        delete scope.data.text;
        let words = Object.values(scope.data);

        element.html(text.split(" ").map(function(w) {
          let index = words.indexOf(w);
          return index !== -1 ? '<span class="word' + (index + 1) + '">' + w + '</span>' : w;
        }).join(" "));
      }
    };
  });
.word1 {
  background-color: yellow;
}

.word2 {
  background-color: green;
}

.word3 {
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <highlight data="response"></highlight>
</div>