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?

1
  • I think this solution is good enough. Commented Sep 22, 2013 at 13:04

3 Answers 3

9

You can try an use the ngCloak directive.

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.