AngularJS – Show a loading image on HTTP Requests

Date Posted: November 27, 2015, 7:01 am


Directive

Add this directive to your app:

1
2
3
4
5
6
7
8
9
10
11
12
13
var app = angular.module('tutorialWebApp', ['ngRoute']);
app.directive('loading', function () {
    return {
        restrict: 'E',
        replace:true,
        template: '<p><img src="img/loading.gif"/></p>', // Define a template where the image will be initially loaded while waiting for the ajax request to complete
        link: function (scope, element, attr) {
            scope.$watch('loading', function (val) {
                val = val ? $(element).show() : $(element).hide();  // Show or Hide the loading image  
            });
        }
    }
});

Usage: Add this code to before $http.get: $scope.loading = true; then $scope.loading = false; on ajax success

Example

Example usage in a controller:

1
2
3
4
5
6
7
app.controller('PageCtrl', function ( $scope, $http, $routeParams ) {
    $scope.loading = true; // Show loading image
    $http.get('http://example.com/posts').success(function(data){
        $scope.posts = data;
        $scope.loading = false; // hide loading image on ajax success
    });
});

About author


Carl Victor Fontanos

A fine gentleman specializing in front-end and back-end development with extensive experience building high performance web applications that keeps users engaged and help businesses grow.

 
Hire Me