Reputation: 80505
I want to find a clean way to set resolve
for a route.
From what I've seen there's 3 main ways of doing this:
declaring global functions (not good)
anonymous functions (bad if the logic is complicated or if I need the same function in multiple places)
setting a method on the controller function (this doesn't work for me because I don't like having controllers as separate function declarations, instead I just do module(...).controller(...);
Is there a better way to do this then the above, especially if I need a resolve shared between similar routes. (e.g. /people and /people/:personID)
Thanks.
Upvotes: 1
Views: 235
Reputation: 3952
How about creating a .constant
and inject it during your .config
phase? If you look at AngularJS documentation for .constant, you will see that you can define a function as a constant.
So, you should be able to do something like:
app.constant("Resolver", {
"MessageUtils": function () {
return {
get: function (message) {
return "MUTIL: " + message;
}
}
}
});
Then you would use it as:
app.config(function ($routeProvider, Resolver) {
$routeProvider.when("/home", {templateUrl: ..., resolve: Resolver, ...})
...
Here is a working plunker:
http://plnkr.co/edit/psuYHu4rtlp4o42ZgqVs?p=preview
I had a similar request in my angularAMD project and I created a function called .route
to help me set the resolve property when defining routes. Here is a link to the code.
Upvotes: 3