Angularjs 如何在 div 中突出显示文本,如果它等于某些关键字



我有一个带有属性wordsdiv,其中包含一些用空格分隔的关键字。

 <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>

我想通过添加称为highlightclass来动态突出显示与段落中的关键字匹配的所有单词。如何在 Angularjs 中做到这一点?

这是预期结果:

.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>

试试这个解决方案。

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>

在 AngularJS 中,对于div 中的突出显示文本没有什么特别之处。但我认为您可以使用ng-class来添加动态类。

阅读文档 NG 类

您可以创建一个简单的指令:

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);
        }
    }
});

看到这个 jsfiddle

最新更新