AngularJS – Spinner

Sometimes a back-end service is slow……………….or slower… You want to notify your user that the page isn’t finished yet. With small changes you can create this functionality into your angularjs application. Below you can read an example how you can do it.

Create a new Service-javascript file “loadingservice.js” 


angular.module('LoadingService', [])
 .config(function ($httpProvider) {
 $httpProvider.responseInterceptors.push('myHttpInterceptor');
 var spinnerFunction = function (data, headersGetter) {
 // todo start the spinner here
 $('#loading').show();
 return data;
 };
 $httpProvider.defaults.transformRequest.push(spinnerFunction);
 })
// register the interceptor as a service, intercepts ALL angular ajax http calls
 .factory('myHttpInterceptor', function ($q, $window) {
 return function (promise) {
 return promise.then(function (response) {
 // do something on success
 // todo hide the spinner
 $('#loading').hide();
 return response;

}, function (response) {
 // do something on error
 // todo hide the spinner
 $('#loading').hide();
 return $q.reject(response);
 });
 };
 })

After that you put a div into your index.html file with id=”loading” and in the bottom a ref to your “loadingservice.js” -file


..........

<body>
<div id="loading"></div>
<div class="container">

.......

<script src="/js/services/loadingservice.js"></script>

In the app.js you add the module ‘LoadingService’


var demoApp = angular.module('demoApp',['ngRoute','gpioServices','LoadingService'])

You go to a site where you generate a spinner “ajax-loader.gif”.

Place the image in your img directory

Add the following CSS code in your app.css file


#loading {
 position: absolute;
 left:50%;
 top:50%;
 width: 100px;
 height: 100px;
 display: none;
 background-image: url('/img/ajax-loader.gif');
}

ajax-loader