Tom Tom - 1 year ago 122
AngularJS Question

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).


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

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

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


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.
$(".click").on("click", function(){
var element = "<button ng-click='doSomething()'>This will not work</button>";

What am I doing wrong? Am I missing something?

Tom Tom
Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download