A_user A_user - 28 days ago 8
AngularJS Question

AngulaJs ng-click in expression html

I am displaying HTML in a AngularJS expression.

In My HTML

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


And In My Controller

$scope.myText = $sce.trustAsHtml("<div class='my-style' ng-click='onClick(10)'>click me</div>");

$scope.onClick = function(value)
{
console.log("onClick: value:"+value);
}


But I am not able to get the click event

UPDATE

In one of the question I see it has be described about how to add HTML tags in the text or how to compile HTML. But my question is related to how to get ng-click event from the complied HTML. I don't see any of the answers providing this solution.

Answer

Sorry for again writing the code : First give a unique id to your div :

        <div id="test"></div>

Then Change that code to below one:

   var myText = "<div class='my-style' ng-click='onClick(10)'>click me</div>";

    var element = angular.element(document.querySelector('#test'));
    var generated = element.html(myText);
    $compile(generated.contents())($scope);

This will manage your code to work. cheers!