AngularJS – Show a loading image on HTTP Requests
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 }); }); |
Do you need help with a project? or have a new project in mind that you need help with?
Contact Me