AngularJS过滤器将html作为字符串返回

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将替换为&lt;a href="http://www.google.com" target="_blank"&gt;http://google.com&lt;/a&gt;.这显然不是一个可点击的链接,这是我的目标.

我不确定为什么会这样.关于如何预防/修复它的任何想法?谢谢.

Jol*_*hic 7

尝试使用ngBindHtmlUnsafe指令将过滤器生成的HTML应用为元素的实际innerHTML内容,如下所示:

<span ng-bind-html-unsafe="event.description | parseUrl"></span>
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,新版AngularJS中没有这样的指令 (4认同)