FaizFizy
FaizFizy

Reputation: 459

Highlight multiple words using AngularJS filter

I'm using AngularJS and at the moment I only manage to highlight a single word in a text. But I want to highlight multiple words using different colors.

Using this response from network call:

{
    "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"
}

I want to display the text like this:

results

Upvotes: 2

Views: 1124

Answers (2)

Weedoze
Weedoze

Reputation: 13953

Here is a way of doing it while keeping your data structure.

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>

Upvotes: 1

prodigyX12
prodigyX12

Reputation: 21

here is other way of doing bear's work 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);

Upvotes: 2

Related Questions