Saturday, June 22, 2019

Angularjs resolve with controller as string

Answer


Answer




My style of writing angular controllers is like this (using controller name instead of function)



angular.module('mymodule', [
])
.controller('myController', [
'$scope',
function($scope) {

// Some code here

}
]);


What I need now is when providing i routes I want to define resolve part:



 $routeProvider.when('/someroute', {
templateUrl: 'partials/someroute.html',

resolve: myController.resolve}) // THIS IS THE CRITICAL LINE


Since controller is defined as a name how to accomplish resolve part bellow?



To clarify more in details I want to load some data from server before route is resolved and then use these data in controller.



UPDATE: To be more precise I want each module has its "resolve" function that will be called before root with that controller is executed. Solution in this post (answered by Misko Hevery) does exactly what I want but I don't have controllers as functions but as a names.


Answer



The controller definition and resolve parts are to be specified separately on the route definition.




If you define controllers on a module level you need to reference them as string, so:



 $routeProvider.when('/someroute', {
templateUrl: 'partials/someroute.html',
controller: 'myController',
resolve: {
myVar: function(){
//code to be executed before route change goes here
};

});


The above code also shows how to define a set of variables that will be resolved before route changes. When resolved those variables can be injected to a controller so taking the example from the snippet above you would write your controller like so:



.controller('myController', ['$scope', 'myVar', function($scope, myVar) {
// myVar is already resolved and injected here
}
]);



This video might help as well: http://www.youtube.com/watch?v=P6KITGRQujQ


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...