Reputation: 6787
Let me give a sample code to better explain .Below is the code :
$routeProvider
.when("/b/:param",{
templateUrl:"main.html"
controller:"MainCtrl"
})
.when("/c/:param",{
templateUrl:"main.html"
});
Now from the above code you can see that for one route I have specified the controller that is to be assigned to the view and for the other I didn't add the controller property so for that route there won't be any controller assigned on the page .
Now my question :
When I don't specify the controller property in the route is there any other way that I can assign the controller for that route dynamically?
I have gone through some of the SO pages related to this, one of which is -> dynamically loading the controller in angularjs $routeProvider
Now I have tried some solutions from the post above which didn't work for me .If any from them works please give me more information on how to implement them .
Solutions like setting controller within page or using ui-router are not the type of solutions I am looking for .So please don't give answers like that .
I tried setting controller using some of the functions available through $controllerProvider & $controller , $routeProvider & $route but didn't work out .I am still not sure if using them I can do the task if they do please answer how to use them .
If question still remains unclear please add a comment below this question .Thanks .
Upvotes: 2
Views: 98
Reputation: 223259
Apparently, it is ngView
directive (one of them) which is responsible for providing the route with relevant controller. And it looks like a good place for the patch. ngView
directives count varied from 1 to 2 with time, the target is the last one.
app.decorator('ngViewDirective', function ($delegate, $route, $injector) {
var ngViewHelper = $delegate[$delegate.length - 1];
var compile_ = ngViewHelper.compile || function () {};
var link_ = ngViewHelper.link;
var link = function () {
var current = $route.current;
if (current.controllerProvider) {
current.controller = $injector.invoke(current.controllerProvider);
}
link_.apply(null, arguments);
}
ngViewHelper.compile = function () {
compile_.apply(ngViewHelper, arguments);
return link;
};
return $delegate;
});
It provides controllerProvider
parameter for the route, similar to the one from ui-router (sorry for that).
controllerProvider
is basically a function that makes use of dependency injection ($route
and $routeParams
are surely welcome there) and returns a controller as a string, a construction function, or no controller at all (undefined
).
...
.when("/:id", {
controllerProvider: function ($routeParams) {
var controller;
if ($routeParams.id == 'foo')
controller = 'FooController';
else if ($routeParams.id == 'bar')
controller = function ($scope) { ... };
return controller;
}
});
Upvotes: 1