2017-02-21 62 views
1

我使用的是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

你可以改变数据结构或者是外部终点? 如果你可以改变或适应数据结构,你可以做这样的事情[JsFiddle,我刚刚创建...](http://jsfiddle.net/j28kmq42/14/) –

+1

@ The.Bear我可能要求改变,但我不确定是否有可能。无论如何,谢谢你的例子。我会根据它来修补,看看我能否找到方法。真的很感谢你帮助我的时间! –

回答

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>

+0

无论如何,我可以使用CSS手动设置颜色。例如'.word1 {0}背景颜色:黄色; } .word2 {background_color:green; } .word3 {background_color:blue; background-color:blue; }' –

+0

我最终改变了@ The.Bear提供的响应格式和修改过的代码示例,但是这实际上回答了这个问题。 :) –

1

这里是做熊的工作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); 
相关问题