Ludo
Ludo

Reputation: 5280

Most optimize way to load datas to display on router's controller

I need to build a User that can be the resut of different REST API call (each way comes from a specific route).

Let's say for this example that we can visit:

then, i have 3 different controllers:

This way is not good because the userCtrl is called before the $http callback (from the router's controllers), so the User is actually empty into the page (i was hopping it will be automatically updated).

Before i try to manage with it (using $rootScope.$apply()), i am wondering what is the more optimize way to do this kind of process (loading datas from router's controller then display it).

Do you use as many controllers as i do ? Do you process these REST APIs calls in the same controller that "bind" your view ? I am interesting to know !

Upvotes: 0

Views: 138

Answers (1)

Brocco
Brocco

Reputation: 64843

When you define your routes you can define an additional value named resolve which is an object where each field is a promise that when resolved will be injected into your controller:

Route Definition:

when('/user/:pseudo', {
    templateUrl: 'views/user.html',
    controller: 'userFromPseudoCtrl'
    resolve: {dataNeeded: userPseudoService.getUserData()});

Service (new):

angular.module('Test').service('userPseudoService', function($http){
    return $http.get('/getUserFromPseudo/test');
});

Controller:

angular.module('Test').controller('userFromPseudoCtrl', function(dataNeeded){});

The route will not change until the promise is resolved.

Upvotes: 0

Related Questions