0

In my Angular app, I receive some HTML as a string from an API and then I want to render it in the page. So I do:

var myHtml = $sce.valueOf(inputString);

return myHtml;

And then I include it in my template:

<div ng-bind-html="myHtml"></div>

This works fine. But before I render it, I also want to make some changes to the text content of the HTML nodes. (I don't want to do this to the original inputString because it's hard to avoid affecting HTML tags.) So I tried:

var myHtml = $sce.valueOf(inputHtml);

// myHtml is an object of type TrustedValueHolderType
// now I want to access the HTML nodes inside it so I do:

for (var i = 0; i < myHtml.length; ++i) {
  if (myHtml[i].nodeType === 3) {
    myHtml[i].nodeValue = myHtml[i].nodeValue.replace(/a/, 'b');
  }
}

return myHtml;

And then include it in my template:

<div ng-bind-html="myHtml"></div>

But this doesn't work because myHtml is not a list of nodes but an object of type TrustedValueHolderType and I cannot access the HTML nodes inside it.

Joe Gatt
  • 2,197
  • 3
  • 15
  • 19
  • Does it throw a particular error? Have you tried performing the replace before you run `$sce.valueOf(inputHtml)`? – Ankh Mar 01 '16 at 09:50
  • import the sanitize module – Hadi J Mar 01 '16 at 09:53
  • Possible duplicate of [Angular sanitize / ng-bind-html not working?](http://stackoverflow.com/questions/14726938/angular-sanitize-ng-bind-html-not-working) – Joe Clay Mar 01 '16 at 09:56
  • @Ankh Thanks. I've edited the question to clarify my problem. It doesn't throw any error because it simply doesn't iterate through the object. I can do the replace when the input is still a string but then it's tricky and hacky to avoid changing the HTML tags. – Joe Gatt Mar 01 '16 at 12:49

0 Answers0