(function () {
angular.module('loaderApp', [])
// HTTP interceptor to auto-toggle loader during $http requests
.factory('loaderInterceptor', ['$q', 'LoaderService', function($q, LoaderService) {
return {
request: function(config) {
LoaderService.show();
return config;
},
response: function(response) {
LoaderService.hide();
return response;
},
responseError: function(rejection) {
LoaderService.hide();
return $q.reject(rejection);
}
};
}])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push('loaderInterceptor');
}])
.service('LoaderService', ['$timeout', function($timeout) {
var _visible = false;
return {
show: function() {
_visible = true;
},
hide: function() {
// optional small delay to avoid flicker
$timeout(function() {
_visible = false;
}, 100);
},
isVisible: function() {
return _visible;
}
};
}])
.controller('MainCtrl', ['$timeout', '$http', 'LoaderService', function($timeout, $http, LoaderService) {
var vm = this;
vm.loading = false;
// Watch the service's visibility
vm._syncLoader = function() {
vm.loading = LoaderService.isVisible();
};
// Poll sync (could also use $scope.$watch with a getter)
setInterval(vm._syncLoader, 100);
// Manual toggle example
vm.doManualAction = function() {
vm.loading = true;
// simulate some async work
$timeout(function() {
vm.loading = false;
}, 1500);
};
// HTTP call example (interceptor manages loader)
vm.doHttpAction = function() {
// Example: simulate HTTP call (you can replace with real endpoint)
$http.get('https://jsonplaceholder.typicode.com/posts/1')
.then(function(resp) {
console.log('HTTP success', resp.data);
})
.catch(function() {
console.log('HTTP error');
});
};
}]);
})();