Question

Hello I have bind some HTML elements. Take a look at below code

<DIV ng-bind-html-unsafe="myHTML"></DIV>

In controller code is

$scope.myHTML="<DIV ng-click="myFunc()"></DIV>"
$scope.myFunc= function(){
alert("TEST");
}

here my html is correctly loaded. When I click on the div I am not able to get an alert.

Was it helpful?

Solution

ng-bind-html-unsafe does not support directive. We have to somehow compile the bound html.

Try compiling it by writing a directive:

app.directive("compile",function($compile,$timeout){
    return {
       priority:-1,
       link:function(scope, element, attrs) {
         $timeout(function(){
           $compile(element.contents())(scope);
         });

       }
    }
});

Use it:

<div ng-bind-html-unsafe="myHTML" compile></div>

DEMO

Another solution is writing our own ng-bind-html

app.directive("myNgBindHtml",function($compile){
    return {
       link:function(scope, element, attrs) {

         scope.$watch(attrs.myNgBindHtml,function(value){
           element.html(value);
           $compile(element.contents())(scope);
         })
       }
    }
});

DEMO

OTHER TIPS

You have a syntax error in your code:

$scope.myHTML="<DIV ng-click="myFunc()"></DIV>"

You should use single quotes around myFunc(), like this:

$scope.myHTML="<DIV ng-click='myFunc()'></DIV>"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top