Reputation: 14282
I am trying to define a generic route which will handle most of request. Adding a route for each and every feature addition is what I feel not good and not maintainable.
So my target is to write a generic route and resolve the decencies dynamically, which include resolving all dependent controller & service files, resolving templateUrl and resolving controller name. I can resolve/construct everything except controller name. Please help me a way around
My route with a custom resolver:
$routeProvider
.when('/:module/:controller/:action?', routeResolver.resolve())
Inside my custom resolver:
function routeResolverProvider(){
this.$get= function(){
return this;
}
this.resolve = function (options) {
var route = {};
route.templateUrl = function (params) {
var path = String.format('/app/components/{0}/{1}.view.html', params.module, params.controller);
return path;
};
//================================================================================
route.controller='THIS IS WHAT I WANT TO CONSTRUCT FROM ROUTE as templateUrl'
//================================================================================
route.resolve = {
loadDependencies: ['$q', '$rootScope', '$route', function ($q, $rootScope, $route) {
// MY RESOLVE LOGIC HERE
// I construct dependent file path from route values
// String.format('/app/components/{0}/{1}.controller.js', params.module, params.controller);
}]
};
return route;
}}
app.provider('routeResolver', routeResolverProvider)
Some good articles: https://github.com/angular/angular.js/wiki/Understanding-Dependency-Injection https://medium.com/opinionated-angularjs/advanced-routing-and-resolves-a2fcbf874a1c
Upvotes: 2
Views: 948
Reputation: 14282
Thanks a lot Dan, I was looking exactly for this kind also. So I modify my resolver as and finally its bingo.
this.$get = ['$rootScope', '$scope', '$route', '$controller', function () {
return this;
}];
route.controller = function ($rootScope, $scope, $route, $controller) {
var params = $route.current.params;
$controller(params.controller.toLowerCase() + 'Controller', {$scope: $scope});
}
Finally I solved my issue but would like to discuss the possible disadvantages of this approach.
Upvotes: 0
Reputation: 6280
If I understand your question correctly, then you want to be able to instantiate a controller by name.
This is possible in AngularJS as explained under Testing Controllers.
You have to use the $controller
service like this:
$scope = $rootScope.$new();
$controller('NamedController', {$scope: $scope});
Here is a working plunker: http://plnkr.co/edit/AVCEdLS9zhIzCyZgcXZF?p=preview
Upvotes: 1