How to apply jquery after AngularJS partial template is loaded

VAAA picture VAAA · Mar 8, 2014 · Viewed 28.1k times · Source

I have a simple website that implements jQuery in order to create a Slider with some images in the Index.html top banner.

Now, I want to use AngularJS so I'm breaking the HTML code into separate partials.

  1. Header
  2. Footer
  3. Top Banner

If I run the Index.html in the original version (without applying AngularJS patterns) then I can see the slider working perfect.

When applying AngularJS patterns, I moved the top banner HTML to a partial html and then applied ng-view to the div where the top banner is originally located.

var app = angular.module('website', ['ngRoute']);
app.config(function($routeProvider) {
    $routeProvider.
    when('/about',{templateUrl:'app/partials/about.html'}).
    when('/contact',{templateUrl:'app/partials/contact.html'}).
    otherwise({redirectTo:'/home',templateUrl:'app/partials/home.html'})
});

When I refresh the page the slider is not working, is rendered as simple html without any jQuery effect, is really a mess.

This partials has some jQuery plugins that usually activates by document.ready. But this event not fire when angular load partial in ng-view. How can i call this event to initialize jQuery plugins?

Any clue how to fix this?

Appreciate any help.

Answer

Aaron picture Aaron · Aug 5, 2014

When you specify your routes, you can also specify a controller, so your routes would look like this:

var app = angular.module('website', ['ngRoute']);
app.config(function($routeProvider) {
    $routeProvider.
        when('/about',{templateUrl:'app/partials/about.html', controller: 'aboutCtrl'}).
        when('/contact',{templateUrl:'app/partials/contact.html', controller: 'contactCtrl'}).
        otherwise({redirectTo:'/home',templateUrl:'app/partials/home.html', controller: 'homeCtrl'})
    });

Now, you can define inside each controller what you want to do, jquery-wise, as part of a function, like this:

angular.module('website').controller('aboutCtrl', ['$scope', function ($scope) {

   $scope.load = function() {
       // do your $() stuff here
   };

   //don't forget to call the load function
   $scope.load();
}]);

Make sense?