這裏是做熊的工作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);
你可以改變數據結構或者是外部終點? 如果你可以改變或適應數據結構,你可以做這樣的事情[JsFiddle,我剛剛創建...](http://jsfiddle.net/j28kmq42/14/) –
@ The.Bear我可能要求改變,但我不確定是否有可能。無論如何,謝謝你的例子。我會根據它來修補,看看我能否找到方法。真的很感謝你幫助我的時間! –