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
- <!DOCTYPE html>
- <html>
- <head>
- <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>
- <script src="script.js"></script>
- </head>
- <body ng-app="myApp" ng-controller="myController">
- <h1>Loading spinner</h1>
- <div data-loading> </div>
- <div>
- <ul ng-repeat="student in students">
- <li>{{student.name}}</li>
- </ul>
- </div>
- <button ng-click="loadData()" class="btn btn-primary">Click for Load data</button>
- </body>
- </html>
Complete code for JavaScript
- angular.module('myApp', [])
- .directive('loading', ['$http' ,function ($http)
- {
- return {
- restrict: 'A',
- template: '<div class="loading-spiner"><img src="http://www.nasa.gov/multimedia/videogallery/ajax-loader.gif" /> </div>',
- link: function (scope, elm, attrs)
- {
- scope.isLoading = function () {
- return $http.pendingRequests.length > 0;
- };
-
- scope.$watch(scope.isLoading, function (v)
- {
- if(v){
- elm.show();
- }else{
- elm.hide();
- }
- });
- }
- };
- }])
- .controller('myController', function($scope, $http) {
- $scope.loadData = function() {
- $scope.students = [];
- $http.get('studentData.json')
- .success(function(data) {
- $scope.students = data[0].students;
- });
- }
-
- });
JSON Data for sample test for service
- [{
- "students":
- [
- { "id": 1, "name": "Vivek" },
- { "id": 2, "name": "Praveen" },
- { "id": 3, "name": "Uday" },
- { "id": 4, "name": "Santosh" }
- ]
- }]
Below is the link for running the sample code.
http://plnkr.co/edit/6TXpVKVjeCBHZ2bW9Fw6?p=preview