我想要一个指令来根据搜索字符串突出显示元素中的文本。
大多数可用的解决方案都使用筛选器而不是指令,其用法如下:
<div ng-html-bind-unsafe="This is the contents for this div | highlight:highlightText"></div>这是一个example
我宁愿使用指令而不是过滤器,因为我不喜欢将元素的内容放在ng-html-bind属性中的想法。我觉得元素的内容应该在它里面。
不管怎样,我为此写了一个指令,但我想知道是否有更好的方法来写它。我觉得这不是最有效的方法。这是fiddle。请注意,<code>元素中的文本未突出显示。这是因为.contents()只返回元素的直接子节点和文本节点。除非有一种非常简单的方法来递归每个子元素的内容,否则这种行为是很好的。
提前谢谢。
发布于 2014-09-10 13:33:17
为了遍历每个子元素的内容,可以使用递归。将用于添加荧光笔和删除高亮笔的代码放入一个函数中,并为每个子元素调用这些函数。
.contents()返回一个Jquery对象。如果是node.nodeType === 1,则将其转换为角度元素,并再次对其调用contents()。
/*Function to add Highlighters*/
scope.addHighlight = function (elm, value) {
angular.forEach(elm.contents(), function (node) {
if (node.nodeType === 3 && scope.needle.test(node.nodeValue)) {
node = angular.element(node);
node.after(node[0].nodeValue.replace(scope.needle, '<span class="highlight">$1</span>')).remove();
} else if (node.nodeType === 1) {
node = angular.element(node);
if (node.contents().length > 0) scope.addHighlight(node, value);
}
});
}
/*Function to remove current Highlighters*/
scope.removeHighlight = function (elm, value) {
angular.forEach(elm.contents(), function (node) {
nodetype = node.nodeType;
node = angular.element(node);
if (node[0].nodeName === 'SPAN' && node.hasClass('highlight')) {
node.after(node.html()).remove();
elm[0].normalize();
}
if (node.children().length > 0 && nodetype === 1) scope.removeHighlight(node, value);
});
}这是更新后的fiddle。
https://stackoverflow.com/questions/23653309
复制相似问题