Angularjs loading screen on ajax request

Instead of setting up a scope variable to indicate data loading status, it is better to have a directive does everything for you:

angular.module('directive.loading', [])

    .directive('loading',   ['$http' ,function ($http)
    {
        return {
            restrict: 'A',
            link: function (scope, elm, attrs)
            {
                scope.isLoading = function () {
                    return $http.pendingRequests.length > 0;
                };

                scope.$watch(scope.isLoading, function (v)
                {
                    if(v){
                        elm.show();
                    }else{
                        elm.hide();
                    }
                });
            }
        };

    }]);

With this directive, all you need to do is to give any loading animation element an ‘loading’ attribute:

<div class="loading-spiner-holder" data-loading ><div class="loading-spiner"><img src="https://stackoverflow.com/questions/17144180/..." /></div></div>

You can have multiple loading spinners on the page. where and how to layout those spinners is up to you and directive will simply turn it on/off for you automatically.

Leave a Comment