Track to see when a view changes in angularjs

Does anyone know how to make angular fire an event when the view has changed? Or right when a view is requested and downloaded? I’m trying to add loading animations for when pages change.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

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>');

         * 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");
                $(domElement).css("position", "inherit");

Please note, $.active is undocumented.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply