Dynamic content added with AngularJS click event not working on the added content

app.controller('MainCtrl', function($scope,$compile) {

    var btnhtml="<button type="button" ng-click="addButton()">Click Me</button>";
    var temp = $compile(btnhtml)($scope);

    //Let's say you have element with id 'foo' in which you want to create a button
    angular.element(document.getElementById('foo')).append(temp);

   var addButton = function(){
       alert('Yes Click working at dynamically added element');
   }

});

you need to add $compile service here, that will bind the angular directives like ng-click to your controller scope. and dont forget to add $compile dependency in your controller as well like below.

here is the plunker demo

Leave a Comment