Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide template while loading in AngularJS

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?

like image 368
Kirill Ryabin Avatar asked Sep 22 '13 12:09

Kirill Ryabin


2 Answers

You can try an use the ngCloak directive.

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

like image 114
Harshad Avatar answered Oct 20 '22 18:10

Harshad


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
like image 6
Rafal Pastuszak Avatar answered Oct 20 '22 17:10

Rafal Pastuszak