What is the better solution to hide template while loading data from server?
My solution is using $scope
with boolean variable isLoading and using directive ng-hide
, ex: <div ng-hide='isLoading'></div>
Does angular has another way to make it?
What is the better solution to hide template while loading data from server?
My solution is using $scope
with boolean variable isLoading and using directive ng-hide
, ex: <div ng-hide='isLoading'></div>
Does angular has another way to make it?
Share Improve this question edited Oct 18, 2013 at 11:45 Kirill Ryabin asked Sep 22, 2013 at 12:49 Kirill RyabinKirill Ryabin 1931 gold badge2 silver badges15 bronze badges 1- I think this solution is good enough. – HasanAboShally Commented Sep 22, 2013 at 13:04
3 Answers
Reset to default 9You can try an use the ngCloak directive.
Checkout this link http://docs.angularjs.org/api/ng.directive:ngCloak
The way you do it is perfectly fine (I prefer using state='loading' and keep things a little bit more flexible.)
Another way of approaching this problem are promises and $routeProvider resolve
property.
Using it delays controller execution until a set of specified promises is resolved, eg. data loaded via resource services is ready and correct. Tabs in Gmail work in a similar way, ie. you're not redirected to a new view unless data has been fetched from the server successfully. In case of errors, you stay in the same view or are redirected to an error page, not the view, you were trying to load and failed.
You could configure routes like this:
angular.module('app', [])
.config([
'$routeProvider',
function($routeProvider){
$routeProvider.when('/test',{
templateUrl: 'partials/test.html'
controller: TestCtrl,
resolve: TestCtrl.resolve
})
}
])
And your controller like this:
TestCtrl = function ($scope, data) {
$scope.data = data; // returned from resolve
}
TestCtrl.resolve = {
data: function ($q, DataService){
var d = $q.defer();
var onOK = function(res){
d.resolve(res);
};
var onError = function(res){
d.reject()
};
DataService.query(onOK, onError);
return d.promise;
}
}
Links:
- Resolve
- Aaa! Just found an excellent (yet surprisingly similar) explanation of the problem on SO HERE
That's how I do:
$scope.dodgson= DodgsonSvc.get();
In the html:
<div x-ng-show="dodgson.$resolved">We've got Dodgson here: {{dodgson}}. Nice hat</div>
<div x-ng-hide="dodgson.$resolved">Latina music (loading)</div>