0

i have simple a index.html page, where i include some htmls files with angular.js

<div data-ng-include="'header.html'"></div>

with this function I include the header into my index page, everything works fine.

i have now a simple alert function:

$('#myButton').click(function(){
    alert('hello');
});

and i have the simple div:

<div id="myButton">test</div>

if i include the div into my index.html everything works fine - but if i include the same div into the header.html which is included by the angular.js there is no reaction or error...

I think the id is then not known to the javascript call.
Any idea, i can get this working? I don't want to give up on the includes....

1
  • 1
    Is there a reason you are not using ng-click? Commented Apr 10, 2013 at 12:16

2 Answers 2

2

The reason is, you are inserting after the document is loaded. So, you need to delegate and manipulate the function this way:

$('body').on('click', '#myButton', function(){
    alert('hello');
});

Explanation would be, the DOM is manipulated after the document's load. But before that you are adding this event handler, which is not received by the element. So, you are delegating the event trigger to the body, when it gets changed, this event is added.

Sign up to request clarification or add additional context in comments.

3 Comments

thank you for your answer Praveen Kumar. is it also possible to change something within the included file like `$('body').on('load','#myDiv', function(){ hide();}); ?
Hey, #myDiv doesn't have load event.
i mean: a body on load function for something which is in the included file?
0

EDIT: as Praveen Kuma stated, 'live' is deprecated as of jQuery 1.7+.

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

So don't use this unless you are using an old version of jQuery. However if you really want to and have a good reason for it, this would work:

use 'live'

http://api.jquery.com/live/

$('#myButton').live('click', function(){
    alert('hello');
});

this will keep watch on your DOM even if the element is not present at the time

4 Comments

fair enough, I had no idea :)
thanks for your help Yoeri help, but if it's deprecated i will take the other answer... (downvote was not from me)
I edited my answer to make sure future readers will also learn this :)
@Yoeri Removed the downvote. But people should not follow this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.