AngularJS create html/link/anchor from text (escape/unescape html in view)

大城市里の小女人 提交于 2019-12-03 02:58:13

I think you can use Angular's linky filter for this: https://docs.angularjs.org/api/ngSanitize/filter/linky

You can use it like so:

<p ng-bind-html="post | linky"></p>

You'll have to include Angular's sanitize module for linky to work:

angular.module('myApp', [
    'ngRoute',
    'ngSanitize',
    'myApp.filters', 
    ...

You can use this replace for the string:

'please visit http://stackoverflow.com quickly'.replace(/(http[^\s]+)/, '<a href="$1">$1</a>')

then you'll need to use the $sce service, and ngBindHtml directive.

$sce is a service that provides Strict Contextual Escaping services to AngularJS.

So in your filter you need to wrap links with a tags then return a trusted html using $sce.trustAsHtml:

filter('createAnchors', function ($sce) {
    return function (str) {
        return $sce.trustAsHtml(str.
                                replace(/</g, '&lt;').
                                replace(/>/g, '&gt;').
                                replace(/(http[^\s]+)/g, '<a href="$1">$1</a>')
                               );
    }
})

Working examples: http://jsfiddle.net/T3fFt/11/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!