1

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)

1
  • 3
    see 'resolve:' docs Commented Jan 30, 2014 at 20:10

1 Answer 1

3

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).

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.