Search code examples
javascriptangularjsangularjs-ng-click

Fire ng-click on dynamic element


I want to create dynamic elements with can fire an ng-click event and want to do this with DataTables where the rows are obtained through AJAX and are dynamically created. The problem is that ng-click isn't fired on those row elements. I have recreated the problem in JSBin with another situation (the DataTables part doesn't really matter).

Html

<div id="elements" ng-controller="TestController as controller">
  <button ng-click='doSomething()'>This button will work</button>
  </div>

  <button class="click">Create element</button>

When the Create element button is clicked, a button is added to the DOM in the #elements div. The button within that div is clicked, the console will output something. It does what it has to do when you click the already created button in the #elements div but doesn't with a dynamically created button.

JS

app.controller('TestController', ['$http', '$scope', function ($http, $scope) {
  //The NG function.
  $scope.doSomething = function(){
    console.log('Function fired!');
  };
}]);                                

//Create new element in the #elements div.                                  
(function(){
  $(".click").on("click", function(){
    var element = "<button ng-click='doSomething()'>This will not work</button>";
    $("#elements").append(element);
  });
})();

http://jsbin.com/hakibocabe/edit?html,js,console,output

What am I doing wrong? Am I missing something?


Solution

  • Although @Radmer van der Heyde's answer pretty much explains how to Angular way of adding buttons to the DOM work (which I'm really thankfull of), @Claies suggested me to use Angular DataTables instead of using the normal jQuery DataTables and pointed out some points on how to do this the Angular way.

    I have reviewed the Angular DataTables and am now working with it which pretty much solved my problem. So if you are having the same problem as I had, use Angular DataTables: http://l-lin.github.io/angular-datatables/#/welcome