Angularjs dynamically set attribute

user2282428 picture user2282428 · Sep 10, 2014 · Viewed 92.1k times · Source

I'm trying to dynamically add attribute to div in controller in angular js.

 var table = document.getElementById("div_id").setAttribute("ng-click", "function_name()");
 $scope.$apply();

Everything looks fine, in the debugger i see that attribute was added but it doesn't execute my function. Do you have any ideas how to add attributes to the existing div and how to make it works?

Answer

cevek picture cevek · Sep 10, 2014

You need to recompile your div

var el = angular.element("div_id");
$scope = el.scope();
$injector = el.injector();
$injector.invoke(function($compile){
   $compile(el)($scope)
})

http://jsfiddle.net/r2vb1ahy/