Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a controller that has an assigned value:

$scope.post = 'please visit http://stackoverflow.com quickly';

I have some text in my html:

<p>{{post}}</p>

I would like to make a clickable link of the url (surround it with anchor tags).

I tried to change my html to:

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

Here is a simplified example of the problem:

http://jsfiddle.net/T3fFt/4/

The question is, how can I escape the whole post text, except for the link, which will be surrounded by anchor tags? ?

like image 580
Daan Avatar asked Jan 31 '14 08:01

Daan


2 Answers

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', 
    ...
like image 196
exclsr Avatar answered Oct 13 '22 14:10

exclsr


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/

like image 45
CD.. Avatar answered Oct 13 '22 13:10

CD..