1

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?

4
  • How are you planning on using the html? Is this along the lines of what your looking for: stackoverflow.com/questions/19415394/… Commented Mar 31, 2015 at 13:23
  • What about creating custom directive with dynamic templates similar as this: onehungrymind.com/angularjs-dynamic-templates Commented Mar 31, 2015 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. Commented Mar 31, 2015 at 13:45
  • Would this work then? stackoverflow.com/questions/26064309/… I just tested it and the solution does work. EDIT: nevermind, it just displays the characters, doesn't display them as html Commented Mar 31, 2015 at 14:11

3 Answers 3

0

Instead of using replace you could do something like this:

input = angular.element('<div/>').html(input).text();
return $sce.trustAsHtml(input);
Sign up to request clarification or add additional context in comments.

2 Comments

This seems another solution but is it not more consumptive ?
yeah probably.. maybe safer though
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

Comments

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;
  }

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.