AngularJS wait for data to render a view?

I'm looking into angularJS but I'm still beginner... And I got a simple question that I hope you can answer.

I got the following routing :

app.config(function($routeProvider) {
  $routeProvider
  .when('/', {
    controller:'ListCtrl',
    templateUrl:'list.html'
  })
  .when('/update/:itemId', {
    controller:'UpdateCtrl',
    templateUrl:'update.html'
  })
  [...]
  .otherwise({
    redirectTo:'/'
  });
});

From the "List" view I'm re-root to the "Update" view using location.path :

app.controller('ListCtrl', function($scope, albumFactory, $location, $http) {
    $scope.albums = albumFactory.getList().then(function(albums){
      $scope.albums = albums;
    });
    [...]
    $scope.updateAlbum = function(index) {
      console.log('updateAlbum()');
      $location.path("/update/" + $scope.albums.albums[index].id);
    }

In the Update Controller I need first to retrieve the detail to pre-fill the view. For this I'm using a factory like follow :

app.controller('UpdateCtrl', function($scope, albumFactory, $location, $routeParams, $http) {

    $scope.album = albumFactory.get($routeParams.itemId).then(function(album){
      $scope.album = album;
    });

So my problem is that the view is first rendered (displayed) empty. Once the Ajax call from my factory is done the scope is updated and the view is fill.

Is it possible to wait for the factory reply before rendering the partial view ? Or maybe I'm doing something wrong ?

The aim is to avoid the short time where the view is empty... (not really userfriendly)

Answers


You need to use $route resolves.

app.config(function($routeProvider) {
  $routeProvider
  .when('/', {
    controller:'ListCtrl',
    templateUrl:'list.html'
    resolve : {
      resolvedAlbums: function(albumFactory) {
        return albumFactory.getList();
      }
    }
  }),
  .when('/update/:itemId', {
    controller:'UpdateCtrl',
    templateUrl:'update.html',
    resolve : {
      // you can inject services in resolves, in this case you also need `$route`
      // to get the `itemId`
      resolvedAlbum: function(albumFactory, $route) {
        return albumFactory.get($route.current.params.itemId);
      }
    }
  })
});

You can then inject the resolved data inside the controllers like this:

app.controller('ListCtrl', function($scope, resolvedAlbums) {
  $scope.albums = resolvedAlbums;
  ...
});

app.controller('UpdateCtrl', function($scope, resolvedAlbum) {
  $scope.album = resolvedAlbum;
  ...
});

The view will not be changed until after the data arrives (promise is resolved).


Need Your Help

Secure axis2 with username token

java web-services apache axis2 rampart

Im trying to generate security with username token in axis2 with rampart.