0

I receive an HTML entities string from an API (like this "<p> Some text <br />") and I would like it to be rendered as HTML.

If I use the classical HTML solution with sanitize :

.filter('html',function($sce){
  return function(input){
     return $sce.trustAsHtml(input);
  }
});

I obtain &lt;p&gt; Some text &lt;br /&gt; as string instead of the <p> and <br> being interpreted as HTML.

The only solution I see for now is to realize some replace and to apply the filter after.

Is there a cleaner solution that avoids parsing the string twice?

alex
  • 6,818
  • 9
  • 52
  • 103
ChrisV
  • 233
  • 4
  • 15
  • How are you planning on using the html? Is this along the lines of what your looking for: http://stackoverflow.com/questions/19415394/with-ng-bind-html-unsafe-removed-how-do-i-inject-html – joshwhatk Mar 31 '15 at 13:23
  • What about creating custom directive with dynamic templates similar as this: http://onehungrymind.com/angularjs-dynamic-templates/ – AvgustinTomsic Mar 31 '15 at 13:25
  • @joshwhatk I am actually not searching the same behaviour since I don't have a _html-formatted_ string from the API but a _htmlentities-formatted_ string. Then, all the tags are escaped as unicode characters. Currently, I am replacing all the &xxx; tags by their html equivalent with a homemade function using String.replace and then i use the sce service to interpret the converted string as safe html but I was asking myself if a cleaner solution was available. – ChrisV Mar 31 '15 at 13:45
  • Would this work then? http://stackoverflow.com/questions/26064309/decode-html-entity-in-angular-js I just tested it and the solution does work. EDIT: nevermind, it just displays the characters, doesn't display them as html – joshwhatk Mar 31 '15 at 14:11

3 Answers3

0

Instead of using replace you could do something like this:

input = angular.element('<div/>').html(input).text();
return $sce.trustAsHtml(input);
eladcon
  • 5,815
  • 1
  • 16
  • 19
0

You can create a filter that parse the html entities,just like this:

app.filter('trusted', ['$sce', function($sce) {
 var div = document.createElement('div');
 return function(text) {
     div.innerHTML = text;
     return $sce.trustAsHtml(div.textContent);
 };
}]);

Until this, is more or less what you told. But now, you can do:

<div ng-bind-html="'&lt;p&gt; Some text &lt;br /&gt;' | trusted"></div>

OR

<div ng-bind-html="yourScopeVariable | trusted"</div>

And it will render the desired HTML

Daniel Santiago
  • 205
  • 1
  • 8
0

In Angular this does what you require:

 import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'unescape'
})
export class UnescapePipe implements PipeTransform {

  transform(value: any, args?: any): any {
    const doc = new DOMParser().parseFromString(value, 'text/html');
    return doc.documentElement.textContent;
  }

}
Madis Männi
  • 168
  • 1
  • 5