这是我的第一个Angular Directive。
我正在尝试根据用于查找该内容的搜索字词对html内容进行简单的突出显示。
问题是,这是第一个任期,但不是更多。我想要突出显示所有单词,但是当我替换HTML内容时,我做错了。
这是指令试图做的事情:
1。
该指令应突出显示一个或多个单词。例如。
如果搜索字词是“文档合法”,则应突出显示它们,即使它们不在此订单中。
因此,像“合法的文件”这样的文本应该突出显示,“合法”和“文档”。
2。
如果单词少于3个字符则不会突出显示。
3。
如果找不到该单词,请尝试从中删除最后一个字符,直到其长度小于3.您可以搜索“维度”,搜索引擎可能会返回包含“维度”甚至“角钱”的文本。
以防万一,该应用程序是一个离子应用程序。
这是我的代码。
角度指令:
BLOBs
你可以看到一些奇怪的东西。就像使用$ scope.highlightTerm而不是将highlightTerm var传递给指令一样。我无法让它发挥作用。
如何正确更改元素的HTML?
这是使用指令的模板:
angular.module('starter.directives', [])
.directive('highlightSearchTerms', function($compile) {
return {
restrict: 'A',
scope: true,
link: function($scope, element, attrs) {
$scope.highlightTerm = function(term) {
var html = element.html();
var highlighted = html.replace(new RegExp(term, 'gi'),
'$&');
if (highlighted == null) {
return false;
}
// @see
// I think that the problem is here, it works the
// first time, but the second time it gets here
// the following exception is throwed
// "Cannot read property 'replaceChild' of null"
element.replaceWith(highlighted);
return html != highlighted;
};
var searchTerms = $scope.searchTerms;
if (searchTerms != undefined && searchTerms.length < 3) {
return;
}
var terms = searchTerms.split(' ');
// Try to highlight each term unless the word
// is less than 3 characters
for (var i = 0; i < terms.length; i++) {
var term = terms[i];
// // Try to highlight unless the word is less than 3 chars
while (term.length > 2) {
// If it got highlighted skip to next term
// else remove a character from the term and try again
if ($scope.highlightTerm(term)) {
break;
}
term = term.substring(0, term.length - 1);
}
}
}
};
});
我希望做类似的事情,但我无法让它发挥作用: