Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
199 views
in Technique[技术] by (71.8m points)

jQuery click events not firing within AngularJS templates

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?

question from:https://stackoverflow.com/questions/18876537/jquery-click-events-not-firing-within-angularjs-templates

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...