Jak*_*rsh 7 javascript angularjs angularjs-filter
我创建了一个AngularJS过滤器,可以自动从数据中找到的地址创建可点击链接.过滤器:
app.filter('parseUrl', function() {
var //URLs starting with http://, https://, or ftp://
replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim,
//URLs starting with "www." (without // before it, or it'd re-link the ones done above).
replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim,
//Change email addresses to mailto:: links.
replacePattern3 = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
return function(text, target, otherProp) {
angular.forEach(text.match(replacePattern1), function(url) {
text = text.replace(replacePattern1, "<a href=\"$1\" target=\"_blank\">$1</a>");
});
angular.forEach(text.match(replacePattern2), function(url) {
text = text.replace(replacePattern2, "$1<a href=\"http://$2\" target=\"_blank\">$2</a>");
});
angular.forEach(text.match(replacePattern3), function(url) {
text = text.replace(replacePattern3, "<a href=\"mailto:$1\">$1</a>");
});
return text;
};
});
Run Code Online (Sandbox Code Playgroud)
以下是我如何调用它(在段落中):
<p><strong>Details:</strong> {{event.description | parseUrl}}</p>
Run Code Online (Sandbox Code Playgroud)
这可以正常使用链接代码替换纯文本链接.但是,它将字符串替换为纯文本.例如,www.google.com
将替换为<a href="http://www.google.com" target="_blank">http://google.com</a>
.这显然不是一个可点击的链接,这是我的目标.
我不确定为什么会这样.关于如何预防/修复它的任何想法?谢谢.
尝试使用ngBindHtmlUnsafe指令将过滤器生成的HTML应用为元素的实际innerHTML内容,如下所示:
<span ng-bind-html-unsafe="event.description | parseUrl"></span>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10147 次 |
最近记录: |