Loading Image For Every HTTP Service Call In AngularJS

Whenever we use an HTTP call in AngularJS, we want to show the loading image by default. So here, we are going to see the process with a sample example.

Below is the complete code for index.html, script.js, and studentData.json page.

Complete code for HTML 

  1. <!DOCTYPE html>    
  2. <html>    
  3. <head>    
  4.     <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>    
  5.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>    
  6.     <script src="script.js"></script>    
  7. </head>    
  8. <body ng-app="myApp" ng-controller="myController">    
  9.     <h1>Loading spinner</h1>    
  10.     <div data-loading> </div>    
  11.     <div>    
  12.         <ul ng-repeat="student in students">    
  13.             <li>{{student.name}}</li>    
  14.         </ul>    
  15.     </div>    
  16.     <button ng-click="loadData()" class="btn btn-primary">Click for Load data</button>    
  17. </body>    
  18. </html>    

Complete code for JavaScript 

  1. angular.module('myApp', [])    
  2.  .directive('loading',   ['$http' ,function ($http)    
  3.  {    
  4.      return {    
  5.          restrict: 'A',    
  6.          template: '<div class="loading-spiner"><img src="http://www.nasa.gov/multimedia/videogallery/ajax-loader.gif" /> </div>',    
  7.          link: function (scope, elm, attrs)    
  8.          {    
  9.              scope.isLoading = function () {    
  10.                  return $http.pendingRequests.length > 0;    
  11.              };    
  12.     
  13.              scope.$watch(scope.isLoading, function (v)    
  14.              {    
  15.                  if(v){    
  16.                      elm.show();    
  17.                  }else{    
  18.                      elm.hide();    
  19.                  }    
  20.              });    
  21.          }    
  22.      };    
  23.  }])    
  24.   .controller('myController'function($scope, $http) {    
  25.       $scope.loadData = function() {    
  26.         $scope.students = [];    
  27.         $http.get('studentData.json')    
  28.           .success(function(data) {    
  29.               $scope.students = data[0].students;    
  30.         });    
  31.       }    
  32.           
  33.   });   

JSON Data for sample test for service 

  1. [{    
  2.   "students":     
  3.   [    
  4.     { "id": 1, "name""Vivek" },    
  5.     { "id": 2, "name""Praveen" },    
  6.     { "id": 3, "name""Uday" },    
  7.     { "id": 4, "name""Santosh" }    
  8.   ]    
  9. }]   

Below is the link for running the sample code.

http://plnkr.co/edit/6TXpVKVjeCBHZ2bW9Fw6?p=preview