Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display wait message in AngularJS while data loading?

Tags:

angularjs

I'm new in AngularJS and trying to find the way how to display wait message while data loading? I mean data starts loading, display message and remove it when data loading is done.

I've searched the internet but haven't found anything I need...

like image 752
tesicg Avatar asked Aug 21 '13 13:08

tesicg


3 Answers

<div ng-if="data.dataLoading">
    Loading...
</div>

JS

$scope.data.dataLoading = true;

return someService.getData().then(function (results) {                    
    ...
}).finally(function () {
    $scope.data.dataLoading = false;
});
like image 70
AlwaysALearner Avatar answered Sep 20 '22 17:09

AlwaysALearner


Depends from where you're loading the data. One solution I used was to create a LoadingService

app.factory('LoadingService', function($rootScope) {
    return {
        loading : function(message) {
             $rootScope.loadingMessage = message;
        },
        loaded : function() {
             $rootScope.loadingMessage = null;
        }
    }
}).controller('FooController', function($scope,$http,LoadingService) {

   $scope.loadSomeData = function() {
       LoadingService.loading('Data is loading');

       $http.get('/data').finally(function() {
            LoadingService.loaded();
       });
   };
});

Since I had only one place where the message was being displayed I could use RootScope to handle this. If you want to have a loading message multiple times you could write a directive also to handle this like Codezilla posted

like image 21
Felipe Leusin Avatar answered Sep 23 '22 17:09

Felipe Leusin


Edit: does not work on version 1.3.0 . Use request/response interceptors.

If you want to listen to all requests globally and display a loading widget whenever there's a request pending, you can count the requests using request/response transformers. You simply add a counter and increase on a new request and decrease it on response. I use a provider for that:

$httpProvider
  .defaults
  .transformRequest
  .push(function(data) {
      requestNotificationProvider
      .fireRequestStarted(data);
      return data;
});

And the same for transformResponse. Then the same provider holds the information on how many requests are pending and you can use them in a directive. You can read (& copy/paste the code) a full blog post on that here: http://www.kvetis.com/2014/01/angularjs-loading-widget.html There's a working demo in attached.

like image 42
kvetis Avatar answered Sep 21 '22 17:09

kvetis