42

I am getting JSON data from the server, one of the field contains escaped html (an email body actually):

<html>\r\n<head>\r\n<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">\r\n</head>\r\n<body dir="auto">\r\n<div>Buonasera, ho verificato i dati sul mio account ed il numero di cell che vi ho fornito</div>\r\n<div><br>\r\n<a (more...)

I am getting crazy at trying to render it with AngularJs.

The following is not working:

<div ng-bind-html-unsafe="mail.htmlbody"></div>

Which I believe is normal because the html is in fact escaped. Should I unescape it first? Is Angular capable of unescaping html with some available service?

If I use $sce like this:

scope.mail.htmlbody = $sce.trustAsHtml(scope.mail.htmlbody);

The source html is displayed, inspecting the element I can see the content is quoted. In other words in the page the source html is displayed instead of the html being rendered. Maybe I am missing something?

5
  • why don't you send as proper html from server? Commented Dec 7, 2013 at 15:14
  • It's what I resolved doing to make it work. But I thought was safer to transport the html escaped. Commented Dec 7, 2013 at 15:36
  • Don't see why it would be any safer, or what difference it would make Commented Dec 7, 2013 at 15:40
  • what version of angular are you using? ng-bind-html-unsafe was remove in version 1.2+ in favor of ng-bind-html and $sce service Commented Dec 7, 2013 at 16:08
  • @max Favilli - Were you able to fix this issue?? What is the solution? Commented Sep 16, 2015 at 15:51

2 Answers 2

49

At the same time $sce service was introduced (angular 1.2), support for ng-bind-html-unsafe directive was dropped. The new directive is ng-bind-html. If you use this, the code should work as documented:

 <div ng-bind-html="mail.htmlbody"></div>
Sign up to request clarification or add additional context in comments.

1 Comment

what if i dont want rest of inner html not overwritten and can't create span tag for custom text
16

Use this directive:

<div ng-bind-html="mail.htmlbody"></div>

Don't forget to use angular sanitize on your app module.

check here : http://docs.angularjs.org/api/ngSanitize

1 Comment

@IlanBiala I'll elaborate. He means to add the ngSanitize module to your app as follows: angular.module('myApp', ['ngSanitize']); and also include the angular-sanitize.js script from here ajax.googleapis.com/ajax/libs/angularjs/1.5.5/… (or whichever version you want) .. the ng-bind-html won't work without these. Hope that helps anyone visiting here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.