Track to see when a view changes in angularjs

Solution 1:

Take a look at this thread it looks like the $httpProvider.responseInterceptors are a good place to add this type of thing.

This fiddle shows a good example on where to add code to start/stop a spinner for ajax requests. This fiddle is similar but actually shows and hides a 'Loading...' div.

If you only want to show a spinner when views change you can limit your start/stop code to when content-type equals text/html similar to what this post shows with application/json.

Note: in my tests it looks like the headersGetter()['Content-Type'] in the spinnerFunction is omitted when retrieving my .html files whereas it is populated when making service calls.

Solution 2:

I think a much simpler, adaptable approach would be to use the AngularJS $http.pendingRequests.length call. It returns the pending ajax call count. So when it reaches 0, you're page is done loading.

You could create a directive that inserts a loading div (scrim) on any element and then waits for all ajax calls to resolve and then removes your spinner.

Here's the meat of the code to make your AngularJS directive:

        // Prepend the loading div to the dom element that this directive is applied.
        var scrim = $('<div id="loading"></div>');
        $(scrim).prependTo(domElement);

        /**
         * returns the number of active ajax requests (angular + jquery)
         * $.active returns the count of jQuery specific unresolved ajax calls. It becomes 0 if
         * there are no calls to be made or when calls become finished.
         * @return number of active requests.
         */
        function totalActiveAjaxRequests() {
            return ($http.pendingRequests.length + $.active);
        }

        /**
         * Check for completion of pending Ajax requests. When they're done,
         * remove the loading screen and show the page data.
         */
        scope.$watch(totalActiveAjaxRequests, function whenActiveAjaxRequestsChange() {
            if(totalActiveAjaxRequests() === 0){
                $log.log("done loading ajax requests");
                $(scrim).remove();
                $(domElement).css("position", "inherit");
            }
        });

Please note, $.active is undocumented.