Using jQuery to select an element generated by ng-repeat in Angular JS directive by class?
I've looked at the documentation on the Angular site here , but I'm still a little confused.
I have an Angular directive whose template contains elements created ng-repeat
. Each of these elements has a common class. I am trying to select these elements by class so that I can pass a handler when an event is triggered by an element that belongs to that class.
As far as I can tell from the answer here , I can select these items with jqLite
or angular.element()
. My jQuery is included AFTER Angular. I guess it should be done this way, because I want to select elements of a specific class AFTER Angular that created them via my directive.
I am not trying to use an event .click()
on a class, this is just a proof of concept. I have the following code in my controller associated with the containing directive element:
$(".gallery-image").click(function(){
alert("test");
});
What I'm trying to do should be pretty obvious, I'm just not sure how to deal with this Angular and jQuery cocktail.
How do I select and fire an event handler using jQuery for these elements?
source to share
Use it like this:
$(document).on("click", ".gallery-image", function(){
alert("test");
});
you can't select directly on ".gallery-image"
because none of them are on the page at the moment you bind the click event to them
But you can always use directive ng-click
on elements in ng-repeat
, you don't need to use jQuery to bind the click event.
source to share
If you load jQuery
after Angular
it angular.element
will be used as a simplified version of jQuery: jqLite.
To use jQuery just make sure it is loaded in front of the angular.js file.
Therefore you need to download jQuery first. You can check the console through angular.element === jQuery
.
If you contain ng-repeat
, always use $timeout
to wait for the render to finish. Then you can access the items.
But of course, always use ng-click
instead whenever possible .on('click',...
.
source to share