Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery targeting elements inside angularjs template, doesn't trigger

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?

like image 863
Mihai Marinescu Avatar asked Mar 12 '15 15:03

Mihai Marinescu


2 Answers

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

  1. attach the click to the html element <div ng-class="{hidden: isHidden}" ng-click="{ toggleHidden() }">

  2. create a function that toggle a var to be used in ng-class $scope.toggleHidden = function () { $scope.isHidden = !$scope.isHidden; }

like image 137
Mihnea Belcin Avatar answered Oct 14 '22 12:10

Mihnea Belcin


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/

like image 1
Andrei C Avatar answered Oct 14 '22 13:10

Andrei C