Thursday, April 28, 2016

AngularJS - $compile

Have you ever was obliged to push HTML code from controller with ng-directives, and you were asking yourself why in god it doesn't work.

For example, you've used Bootstrap popover and you need to attach ng-click to a popover item. You did, but it didn't work.

Easily, your HTML needed to be recompiled again to be executable by Angular, and here's why you should $compile to do that.

Simple Example:


$("#MyPopoverDiv").popover({ 
  html: 'true', 
  title: "", 
  content: function() { 
    return $compile("<ul>
      <li id='MyProfile'>
       <span class='glyphicon glyphicon-user'></span>
       Option 1
      </li>
      <li id='Preferences'>
       <span class='glyphicon glyphicon-cog'></span>
       Option 2
      </li>
      <li id='LogOut' ng-click='logout()'>
       <span class='glyphicon glyphicon-log-out'></span>
       Sign out
      </li>
    </ul>")($scope); 
  }, 
  placement:"bottom", 
  trigger:"focus click", 
  template:"" 
}); 

So, instead of just putting your popover content into "content" attribute. You need to use $compile first to make it ready to use ng-directives

content: function(){ 
return $compile(*Your HTML content*)($scope);
}
Don't forget to pass $compile as a dependency on controller initialization.

Cheers