13

I am developing an app using Angularjs and adding HTML using $sce.trustAsHtml() in my page. I want to call a function in above dynamically added content. My html and script as below.

HTML

<div ng-app="ngBindHtmlExample">
  <div ng-controller="ngBindHtmlCtrl">
   <p ng-bind-html="myHTML"></p>
  </div>
</div>

Javascript

angular.module('ngBindHtmlExample', ['ngSanitize'])

.controller('ngBindHtmlCtrl', ['$scope','$sce', function ngBindHtmlCtrl($scope, $sce) {
  $scope.myHTML =$sce.trustAsHtml(
     'I am an <code>HTML</code>string with <a href="#" ng-mouseover="removeExp()">links!</a> and other <em>stuff</em>');
  
    $scope.removeExp = function (){
       console.log('dfdfgdfgdfg');
    }
}]);

jsfiddle

Click Here to see

Community
  • 1
  • 1
Rajnikant Kakadiya
  • 2,185
  • 1
  • 23
  • 30

1 Answers1

46

It's a bit tricky because ng-bind-html will simply insert plain old html and not bother compiling it (so any directives in the html will not be processed by angular.

The trick is finding a way to compile whenever the template changes. For example, you could create a directive that does this. It would look something like:

.directive('compileTemplate', function($compile, $parse){
    return {
        link: function(scope, element, attr){
            var parsed = $parse(attr.ngBindHtml);
            function getStringValue() { return (parsed(scope) || '').toString(); }

            //Recompile if the template changes
            scope.$watch(getStringValue, function() {
                $compile(element, null, -9999)(scope);  //The -9999 makes it skip directives so that we do not recompile ourselves
            });
        }         
    }
});

You can then use it like this:

<p ng-bind-html="myHTML" compile-template></p>

See the working example here:

http://jsfiddle.net/3J25M/2/

Daniel Tabuenca
  • 13,147
  • 3
  • 35
  • 38
  • This worked for me after a tweak. I am using it in an ionic app and it did not like function getStringValue(), only in the emulators mind you. I needed var getStringValue = function(). – Ken Goodridge Aug 27 '15 at 02:05
  • Awesome dude. This helps me – Faris Rayhan Nov 29 '16 at 03:30
  • Could anyone please see this link https://stackoverflow.com/questions/45713677/ng-click-is-not-working-with-return-sce-trustashtml-in-angular-js-without-using?noredirect=1#comment78386257_45713677 – Varun Sharma Aug 17 '17 at 06:30