How to work ng-click with the template in ng bind html?

I had been working on AngularJs recently and I came across a problem where when I found out that ng-click does not work when some string html is drawn using ng bind html directive.

I looked over internet and found couple of questions and some other articles ( here, here ) which tackled similar problem.

The solution I found there was somewhere around to use $compile to compile the html. But that was not working for me according to my requirement(or I didn’t understood that well) as I didn’t want it to compile everytime.

Then I found this real nice and easy hack. The hack is that we replace ng-click with onClick of javascript which does work. And then in the onClick function, we find the scope of the html, and call the required function of the corresponding controller explicitly in there. Below is how its done. πŸ™‚

So earlier we had this in ng-bind-html,

<a ng-click="myControllerFunction()" href="something">

Now either put an id attribute in the anchor tag, or create an empty div with an id attribute set for that, as below, Either,

<a id="myControllerScope" onClick="tempFunction()" href="something">

Or,

<a onClick="tempFunction()" href="something">
<div id="myControllerScope">
div closing tag

Now,Β at the end or some place where you have written your other javascript code, put below code. It should be outside the angular blocks(controller or run or anything else) as it is just another javascript code.


function tempFunction() {
 var scope = angular.element(document.getElementById('myControllerScope')).scope();
  scope.$apply(function() {
    scope.myControllerFunction();
 });
}

Explanation :

In the javascript code, we find the current scope of the html which was being drawn by ng bind html in the scope variable and then calling the respective function which should have been called by ng-click.

Oh Yes, it works like a charm.

Ok Bye. πŸ™‚

Latest Comments
  1. R.P Singh March 28, 2016

Leave a Reply