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

All we need is an easy explanation of the problem, so here it is.

I have a controller that has an assigned value:

$ = 'please visit quickly';

I have some text in my html:


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:

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

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I think you can use Angular’s linky filter for this:

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', [

Method 2

You can use this replace for the string:

'please visit quickly'.replace(/(http[^\s]+)/, '<a href="$1" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener">$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

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" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener">$1</a>')

Working examples:

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply