20

I have to make a queue of all requests simultaneously happening without waiting for the response from the previous request in angularjs.
I have a loading function which shows the loading div each time I change the url route but its not ok to make an arrray of queue in that function.

Can anyone tell me which function is called in angularjs routes when each time I change the url route ?
HEre is the routes code :

angular.module('myApp', ['myApp.directives', 'myApp.services', 'myApp.filters']).config(
    function($routeProvider, $locationProvider, $httpProvider) {
        $locationProvider.html5Mode(false);
        $locationProvider.hashPrefix('!');

        $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

        var loading = function (data, headersGetter) {
            $('loadingDiv').show();
            return data;
        };
        $httpProvider.defaults.transformRequest.push(loading);

        $routeProvider.
        when('/', {
            templateUrl: 'elements/home/home.html',
            controller: homeCtrl
        });
   });
Stewie
  • 60,366
  • 20
  • 146
  • 113
Amb
  • 3,343
  • 7
  • 27
  • 34

2 Answers2

24

You could use something like:

.run( function($rootScope, $location) {
   $rootScope.$watch(function() { 
      return $location.path(); 
    },
    function(a){  
      console.log('url has changed: ' + a);
      // show loading div, etc...
    });
});
garst
  • 6,042
  • 1
  • 29
  • 24
  • but $scope is not defined in routes. – Amb Mar 16 '13 at 05:29
  • you are right, I've edited the answer, $rootScope instead, in a Module.run() initialization function – garst Mar 16 '13 at 06:13
  • 1
    Thanks.. it works but now i want the list of all pending requests in routes or in controller any where.. Do you have any idea ? – Amb Mar 16 '13 at 06:34
24

$route service has a series of events you can monitor using $.on in a controller:

$rootScope.$on("$routeChangeStart", function(args){})

$rootScope.$on("$routeChangeSuccess"....

$rootScope.$on("$routeChangeError"....

See doc $route

You could set ng-show on your element instead of using jQuery and set the variable to true in $routeChangeStart callback and false in $routeChangeSuccess callback.

A good demo for these events: https://github.com/johnlindquist/angular-resolve

Andres
  • 4,323
  • 7
  • 39
  • 53
charlietfl
  • 170,828
  • 13
  • 121
  • 150