Issue
I would like to attach an event listener (e.g. ‘click’) to a programatically added JavaScript generated code (every line of a table). Usually, I would normally do that with jQuery dirty on
method, but it doesn’t work (seems that my selector is too much specific. I don’t know any way to do this in another way…
var STD.prototype.addTableWithEvent(id, eventName, eventFunction)
{
var ident = "webapp_table_"+ id;
var table = angular.element("<table id=\"#"+ ident +"\"></table>");
var line = angular.element("<tr></tr>");
// this is the line not working
jQuery("body").on(eventName, '#'+ ident +' tr', { std: this }, eventFunction);
line.appendTo(table);
this.$compile(table)(this.$scope);
table.appendTo('body');
};
This function is then called this way:
var std = new STD();
std.addTable("example", "click", function() { console.log("working"); });
The table is well added to the page, but the event function is not called when I click. If I change for this :
jQuery("body").on(eventName, 'tr', { std: this }, eventFunction);
Then it’s working but for every table, which is not what I want.
Is there a way to do this with Angular.js or jQuery?
Solution
Try attaching the event to the table instead of the body, and set the selector to delegate it to the <tr>
elements, like so:
table.on(eventName, 'tr', { std: this }, eventFunction);
Answered By – James Fair
Answer Checked By – David Marino (AngularFixing Volunteer)