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

人盡茶涼 提交于 2019-11-27 12:07:48
K.Toress
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

You could also bind the event to your new button.

  $scope.addButton = function() {
    alert("button clicked");
    var btnhtml = '<button type="button">Click Me</button>';
    var newButt = angular.element(btnhtml);
    newButt.bind('click', $scope.addButton);
    angular.element(document.getElementById('foo')).append(newButt);
  }

Updated plunkr.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!