Reputation: 3301
Hi I'm want to load data from a factory before any of my controllers are loaded. I found a way to do it using resolve:
angular.module('agent', ['ngRoute','ui.bootstrap','general_module', 'order_module','customer_module']).config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/customer', {
templateUrl: 'customer_module/partials/customer.php',
resolve:{
'MyServiceData':function(loginvalidation){
// MyServiceData will also be injectable in your controller, if you don't want this you could create a new promise with the $q service
var a=loginvalidation.check_usertype();
}}
}
);
$routeProvider.otherwise({redirectTo: '/customer'});
}]);
But the problem is I would have to duplicate this with every single route. Is there a way in angularjs to write the code once to load the service before any controller is initiated (without duplicating my code)?
Thanks
Upvotes: 1
Views: 157
Reputation: 21762
One thing that I do, is in my controller function, I don't have any code at the root level. Only function declarations. See here:
angular.module('app').controller('TestCtrl',function($scope){
//no code here at root level, except for some init call
init();
function init(){
//some init code
service.getSomeData().then(function(data){
//Tell your controller to run here
$scope.dataLoaded = true;
doSomethingWithData(data);
});
}
function addSomeWatch(){
//some watch code here
}
function foo(bar){
//something crazy
}
});
The only thing that this depends on is that your service calls all return promises, which they should be doing anyways.
angular.module('app').factory('TestService', function(){
return {
getSomeData : function(){
var d = $q.deferred();
$http.get('someurl')
.then(function(resp){
d.resolve(resp);
});
return d.promise;
}
}
});
Upvotes: 1