替换html中的链接,在指令的链接中替换angular元素html

这是我的第一个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);

}

}

}

};

});

我希望做类似的事情,但我无法让它发挥作用:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值