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...
<div ng-if="data.dataLoading">
Loading...
</div>
JS
$scope.data.dataLoading = true;
return someService.getData().then(function (results) {
...
}).finally(function () {
$scope.data.dataLoading = false;
});
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With