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.
Written by Eugeniy
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Js
Authors
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#