Reputation: 7475
This may be a bit of strange case where nobody has ever experienced this before, but I'm posting this on the off-chance that somebody knows something I don't.
I'm using jQuery 2.0.3 and AngularJS.
If I have an anchor in index.html
like so:
# index.html
<a href="#" class="clickme">Click Me</a>
<script type="text/javascript">
$(function() {
$('.clickme').click(function() { console.log("click"); });
});
</script>
Then it works, and when I click it, it outputs 'click'. But when I put that inside a template that I include with the ng-include
attribute, the jQuery all of a sudden doesn't fire. If I place the script inside the template with the anchor though, it DOES fire.
# index.html
<div ng-include="'path/to/template.html'"></div>
# template.html
<a href="#" class="clickme">Click Me</a>
<script type="text/javascript">
$(function() {
$('.clickme').click(function() { console.log("click"); });
});
</script>
This is also the case with using directives which use templates. It's bizarre and causing me a lot of hassle with some drop down menus.
Does anyone know why this is happening?
Upvotes: 40
Views: 34399
Reputation: 78525
Since your clickme
probably isn't available on DOM ready - rather it is pushed into the DOM by Angular when it loads template.html
- you need to use jQuery's event delegation instead of using .click
:
$(document).on("click", ".clickme", function() {
console.log("click");
});
This will ensure jQuery binds onto the document, then monitors for any click events on elements with the clickme
class.
Upvotes: 101