1

I am trying to print to the screen custom html using angular. I am using $sce.trustAsHtml in combination with ng-bind-html to accomplish this. The goal is not only to be able to print this custom html, but that it will retain directives such as ng-click and they will be usuable. Examples I have seen in articles such as follows are promising:

AngularJS render HTML within double curly brace notation

However in my implementation I find that although the html renders correctly including references to ng-click, the directive doesn't seem to work anymore when trying to click on the link I am using it on; here is some sample code:

$scope.htmlExpression = $sce.trustAsHtml("<a ng-click='test();'>Click Me</a>");

$scope.test = function() {
    console.log('Hello World!');
}

<div>
  <p ng-bind-html="htmlExpression"></p>
</div> 

As everything renders fine and nothing appears lost in translation when analyzing the source; I am left feeling as if I have left something out. Any help is appreciated.

Community
  • 1
  • 1
Gedalya
  • 899
  • 4
  • 16
  • 28

1 Answers1

1

Use https://docs.angularjs.org/api/ngSanitize and bind the html. If this does not work, $digest to reboot the digest cycle.

Muaaz Rafi
  • 1,469
  • 2
  • 15
  • 23
  • I am not familiar with these; is there an example I can reference on how to trigger these? – Gedalya Aug 22 '16 at 20:17
  • yeah https://www.sitepoint.com/understanding-angulars-apply-digest/ , you retrigger the cycle. For ngSanitize you just need to include the lib into your module. – Muaaz Rafi Aug 22 '16 at 20:19