You could accomplish that by using resolve
in your routingProvider.
This allows you to wait for some promises to be resolved before the controller will be initiated.
Quote from the docs:
resolve - {Object.=} - An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected and $routeChangeSuccess event is fired.
Simple example
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {templateUrl: 'home.html', controller: 'MyCtrl',resolve: {
myVar: function($q,$http){
var deffered = $q.defer();
// make your http request here and resolve its promise
$http.get('http://example.com/foobar')
.then(function(result){
deffered.resolve(result);
})
return deffered.promise;
}
}}).
otherwise({redirectTo: '/'});
}]);
myVar will then be injected to your controller, containing the promise data.
Avoiding additional DI parameter
You could also avoid the additional DI parameter by returning a service you were going to inject anyways:
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {templateUrl: 'home.html', controller: 'MyCtrl',resolve: {
myService: function($q,$http,myService){
var deffered = $q.defer();
/* make your http request here
* then, resolve the deffered's promise with your service.
*/
deffered.resolve(myService),
return deffered.promise;
}
}}).
otherwise({redirectTo: '/'});
}]);
Obviously, you will have to store the result from your request anywhere in a shared service when doing things like that.
Have a look at Angular Docs / routeProvider
I have learned most of that stuff from that guy at egghead.io
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…