Show spinner GIF during an $http request in AngularJS?

Ajay Beniwal picture Ajay Beniwal · Feb 22, 2013 · Viewed 289.9k times · Source

I am using the $http service of AngularJS to make an Ajax request.

How can a spinner GIF (or another type of busy indicator) be shown while the Ajax request is executing?

I don't see anything like an ajaxstartevent in the AngularJS documentation.

Answer

Josh David Miller picture Josh David Miller · Feb 22, 2013

This really depends on your specific use case, but a simple way would follow a pattern like this:

.controller('MainCtrl', function ( $scope, myService ) {
  $scope.loading = true;
  myService.get().then( function ( response ) {
    $scope.items = response.data;
  }, function ( response ) {
    // TODO: handle the error somehow
  }).finally(function() {
    // called no matter success or failure
    $scope.loading = false;
  });
});

And then react to it in your template:

<div class="spinner" ng-show="loading"></div>
<div ng-repeat="item in items>{{item.name}}</div>