TSR
TSR

Reputation: 20526

Angularjs How to highlight text in div if it equals to some keywords

I have a div with an attribute words that contains some keywords separated by a blankspace.

 <div words="automobile physiology crime">
 The dentist travels every coverage.
 The talent pumps opposite the automobile. 
 The poet shies away under a frightening day.
 The innovative physiology breezes above the ideology.
 A manned waste fusses next to the hardback crime.
 The changing conflict recovers in my fewer sermon.
 </div>

I would like to dynamically highlight all words that matches the keywords in the paragraph by adding class called highlight. How can I do that in Angularjs?

This is the expected results:

.highlight {
background-color: yellow;
}
<div words="automobile physiology crime">
 The dentist travels every coverage.
 The talent pumps opposite the <span class="highlight">automobile</span>. 
 The poet shies away under a frightening day.
 The innovative <span class="highlight">physiology</span> breezes above the ideology.
 A manned waste fusses next to the hardback <span class="highlight">crime.</span>
 The changing conflict recovers in my fewer sermon.
 </div>

Upvotes: 1

Views: 1265

Answers (3)

devqon
devqon

Reputation: 13997

You can create a simple directive:

app.directive("words", function() {
    return {
        link: function(scope, element, attrs) {
            var words = attrs.words.split(' ');
            var html = element.html();

            for (var i = 0; i < words.length; i++) {
                var re = new RegExp(words[i], "g");
                html = html.replace(re, '<span class="highlight">' + words[i] + '</span>');
            }

            element.html(html);
        }
    }
});

See this jsfiddle

Upvotes: 0

VadimB
VadimB

Reputation: 5711

Try this one solution.

angular.module('app', []).directive('words', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var words = element.attr('words').split(' ');
      
      for(var i=0; i<words.length; i++) {
        var r = new RegExp(words[i], 'ig')
        element.html(element.html().replace(r, '<span class="highlight">' + words[i] + '</span>'));
      }
    }
  };
})
.highlight {
  background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" words="automobile physiology crime">
 The dentist travels every coverage.
 The talent pumps opposite the automobile. 
 The poet shies away under a frightening day.
 The innovative physiology breezes above the ideology.
 A manned waste fusses next to the hardback crime.
 The changing conflict recovers in my fewer sermon.
 </div>

Upvotes: 2

Durgpal Singh
Durgpal Singh

Reputation: 11963

In AngularJS nothing special for highlight text in div. But I think you can use ng-class for add dynamic class.

read doc ng-class

Upvotes: 0

Related Questions