Bancarel Valentin
Bancarel Valentin

Reputation: 531

Why this doesn't display HTML

In my angular application, among the data I retrieve, there is some text potentially containing line breaks, links, and other stuffs I need to convert to HTML. So I implemented this function to "convert" those string to html:

$scope.textToHTML = function(text){
    if(!text){return "";}
    var html = text.replace("\r\n", "<br>")// Windows line break
        .replace("\n", "<br>")// Carriage Return
        .replace("\r", "<br>")// Line feed
        .replace("\t", "<span style=\"margin-left: 20px;\"></span>")
        .replace("(https?:\\/\\/[^\\s]*)", "<a href=\"$1\" target=\"_blank\">$1</a>");

    return $sce.trustAsHtml(html); 
}

Then I'm using it as this: <p data-ng-bind-html="">{{textToHTML(company.description)}}</p>.

When I remove data-ng-bind-html, I see the excpected code (escaped) but with it, my <p> is always empty. I read Angular $sce doc, but I must be missing something because I still don't quite understand what trustAs() do...

Is it supposed to return a sort of a string with code that can be interpreted safely ? Or is it supposed to say angular "this string is safe, if you see it in an data-ng-bind-html attribute display it as if !"

Upvotes: 2

Views: 120

Answers (1)

dfsq
dfsq

Reputation: 193251

Correct usage of the ngBindHtml would be:

<p data-ng-bind-html="textToHTML(company.description)"></p>

Upvotes: 3

Related Questions