6

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?

Kirill Ryabin
  • 193
  • 1
  • 2
  • 15

3 Answers3

9

You can try an use the ngCloak directive.

Checkout this link http://docs.angularjs.org/api/ng.directive:ngCloak

Harshad
  • 101
  • 2
6

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
Community
  • 1
  • 1
Rafal Pastuszak
  • 3,100
  • 2
  • 29
  • 31
1

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>

Amaury D
  • 475
  • 4
  • 7