I have an angular app which loads inside the index, different templates with ng-view. In the index, I load all of the script files (angular and jquery), including the main.js file which contains jQuery code written by me. If I target the elements from the index file with jQuery, everything works fine, but if I target the elements inside the template, the jQuery doesn't work.
If I use firebug to debug the jQuery and I put some breakpoints at the beginning of the click function, and inside the function, the code works.
If I put the tags inside the template, with the jQuery code, the code works.
This is my jquery code which I try to run:
$('.text-down-arrow').click(function () {
$('.text-up-arrow').removeClass('hidden');
});
I tried wrapping everything in the main.js file as:
(function ($) {
$(document).ready(function () {...});
})(jQuery);
or without the $(document).ready(function () {});
Anybody knows what causes this or if I should load the jquery inside each template?
Jquery wont do the trick . because at the time the document is ready . that HTML with the arrow is not in yet . angular sets the view at some point
so u want to trigger the click in the angular way with ng-click
attach the click to the html element
<div ng-class="{hidden: isHidden}" ng-click="{ toggleHidden() }">
create a function that toggle a var to be used in ng-class
$scope.toggleHidden = function () {
$scope.isHidden = !$scope.isHidden;
}
As Mihnea pointed out, the element that you're attaching the event handler to doesn't exist in the DOM when you run the script.
Luckily you can use .delegate() to Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
http://api.jquery.com/delegate/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With