Last Updated: March 11, 2019
·
2.413K
· jaxxreal

Page loader solution for AngularJS

Hi, guys! I found a simple and perfect solution for page loader realization for AngularJS projects.


angular('myModule').factory('loaderToggle', ['$rootScope', '$timeout', function($rootScope, $timeout) {
          return {
              'request': function(config) {
                  // I suppose that $rootScope.loader variable used in ng-show directive
                  if (config.withloader) $rootScope.loader = true;
                  return config;
              },

              'response': function(response) {
                  if (response.config.withloader) {
                      // timeout for avoid loader blinking 
                      $timeout(function () {
                          $rootScope.loader = false;
                      }, 500);
                  }
                  return response;
              }
          }
      }]);

// then inject our factory into angular config

angular.module('myModule').config(['$httpProvider', function($httpProvider) {
    // our config lines...
    // then add loaderToggle factory to interceptors array
    $httpProvider.interceptors.push('loaderToggle');
}]);

In the next place simply added withloader prop to $resource config:


angular.module('myModule')
.factory('Posts', function($resource, BACKEND_URI, PERPAGE_LOAD_LIMIT, $rootScope) {
        var $res = $resource(
            BACKEND_URI + "/post:action?json&token=" + $rootScope.token,
            {action: '@action'},
            {
                list: {method: 'GET', params: {action: '/', offset: 0, perpage: PERPAGE_LOAD_LIMIT}, withloader: true},
                add: {method: 'POST', params: {action: '/new'}, withloader: true},
                edit: {method: 'POST', params: {action: '/change_status'}, withloader: true}
            }
        );
        return $res;

});

And that's all! Works for AngularJS 1.2.20.