Reputation: 305
I am developing an angular js application, and i need to run a function, via service provider, before everything else. The function is a get request, which returns two variables in JSON, which returns either true
orfalse
.
If the variable is true, then load another state (i am using ui router). How can i do that?
Upvotes: 2
Views: 146
Reputation: 3025
In angular the document loaded is not really has a good usage, because it is a framework and the we need to count on angular loaded/ready instead. Use angular.module('yourApp').run()
like below:
var app = angular.module('yourApp');
app.run(['$rootScope', '$http', function($rootScope, $http){
$http('http://localhost/status/').then(function(res){
$rootScope.somethingStatus = res; // assuming that your response is either true of false.
});
$rootScope.$watch('somethingStatus', function(nv){
// here is where you know your request has been done...
if(nv === true) {
// ...
}
else if(nv === false) {
// ...
}
});
}]);
NOTE: please aware what run in app.run()
will be fired before any controller initialing or view rendering. So later on when you want to access the value of what you been got. Inject $rootScope
to the controller (or any place) when you needed it.
EDIT: fix some typos. Updated answer again, credit to @georgeawg and @Pierre Emmanuel Lallemant. Thanks you guys for the correction
Upvotes: 3
Reputation: 2569
You should write a controller for the page where you do the request (in order to display something to the user), with a default html view, and when you receive the response, then you change the state to use the desired controller.
Upvotes: 2