I am using the $http
service of angular to make an ajax request.
How to show a loader gif during the ajax request?
I don't see any ajaxstartevent
or similar event in documentation.
I am using the $http
service of angular to make an ajax request.
How to show a loader gif during the ajax request?
I don't see any ajaxstartevent
or similar event in documentation.
Used following intercepter to show loading bar on http request
If you're wrapping your api calls within a service/factory, then you can track the loading counter there (per answer and excellent simultaneous suggestion by @JMaylin), and reference the loading counter via a directive. Or any combination thereof.
API WRAPPER
SPINNER DIRECTIVE
USAGE
Here is my implementation, as simple as a ng-show and a request counter.
It use a new service for all request to $http:
And then you can use your loader base on the number of current calls:
Add this css:
And just in your angular add:
$rootScope.loading = false; $rootScope.loading = true; -> when $http.get ends.
Here's a version using a
directive
andng-hide
.This will show the loader during all calls via angular's
$http
service.In the template:
<div class="loader" data-loading></div>
directive:
by using the
ng-hide
class on the element, you can avoid jquery.Customize: add an
interceptor
If you create a loading-interceptor, you can show/hide the loader based on a condition.
directive:
interceptor:
spinner
whenresponse.background === true;
request
and/orresponse
to set$rootScope.$broadcast("loader_show");
or$rootScope.$broadcast("loader_hide");
more info on writing an interceptor
All answers are or to complicated, or need to set some variables on every request which is very wrong practice if we know the DRY concept. Here simple interceptor example, I set mouse on wait when ajax starts and set it to auto when ajax ends.
Code has to be added in application config
app.config
. I showed how to change mouse on loading state but in there it is possible to show/hide any loader content, or add, remove some css classes which are showing the loader.Interceptor will run on every ajax call, so no need to create special boolean variables ( $scope.loading=true/false etc. ) on every http call.