【发布时间】:2013-07-07 19:44:28
【问题描述】:
我创建了一个 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;
};
});
我是这样称呼它的(在一段中):
<p><strong>Details:</strong> {{event.description | parseUrl}}</p>
这可以正确地用链接代码替换纯文本链接。但是,它用纯文本形式的链接替换它。例如,www.google.com 将被替换为 &lt;a href="http://www.google.com" target="_blank"&gt;http://google.com&lt;/a&gt;。这显然不是一个可点击的链接,这是我的目标。
我不确定为什么会这样。关于如何预防/修复它的任何想法?谢谢。
【问题讨论】:
-
您可能想看看 AngularJS 在 ngSanitize 模块中提供的“linky”过滤器 (docs.angularjs.org/api/ngSanitize.filter:linky)——该过滤器可能已经满足您的需求,并且它的文档支持在有关 ng-bind-html / ng-bind-html-unsafe 指令的答案中提出的建议。
标签: javascript angularjs angularjs-filter