I'm trying to make an asynchronous API call triggered by the onEnter to a new .state
onEnter: function(StatFactory){
StatFactory.getStats(function(res){
console.log("callback");
});
}
what I've noticed so far is that it calls the async function first, then instantiates the controller for the new state and finally fires the callback.
The function will update data inside the factory, but the $scope won't be updated.
I thought maybe I need to force $apply on the new $scope, but I don't know how.
Any idea? (I'm a novice)
As far as I know, onEnter
does not provide you with a $scope
to bind the results to.
You can either call the function upon controller creation (IE controller's definition block) or use the resolve
state param (note: this will cause the state to not be activated if the asynchronous function fails).
Here's an example with resolve
:
$stateProvider.state('home', {
...
//Will wait for the getStats call to end. You can inject the stats to the controller now.
resolve: {
stats: function(StatFactory) { return StatFactory.getStats(); }
},
controller: function($scope, stats){
//Use stats
$scope.stats = stats;
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.