I currently have an AngularJS app with routing built in and it works perfectly with static controller
property assignments. but what I really want to do is to dynamically assign controllers with different routes:
$routeProvider
.when("/Dashboards/:dashboardName",{
templateUrl:function(params) {
return "Dashboards/" + params.dashboardName;
//some ASP.NET MVC calls to return partial views (this part works)
}
})
What I would like to do is to do the same thing about my controller
property here, like:
$routeProvider
.when("/Dashboards/:dashboardName",{
templateUrl:function(params) {
return "Dashboards/" + params.dashboardName;
//some ASP.NET MVC calls to return partial views (this part works)
},
controller: function(params) {
return params.dashboardName+"Controller"; (this part DOESN'T work)
}
})
but as it seems I am get an error saying paramsProvider
is not found
so is there any way I could dynamically load my controller function name in route configuration?
This is possible to do using angular ui-router.
The ui-router lets you specify a "controllerProvider" to specify a function for providing a controller. So the solution would look like this:
$stateProvider
.state("/Dashboards/:dashboardName",{
templateUrl:function($stateParams) {
return "Dashboards/" + $stateParams.dashboardName;
},
controllerProvider: function($stateParams) {
return $stateParams.dashboardName+"Controller";
}
})
I hope it helps!
I solved this issue by not specifying the controller in $routeProvider but instead placing it in the file specified in templateURL.
$routeProvider
.when("/Dashboards/:dashboardName",{
templateUrl:function(params) {
return "Dashboards/" + params.dashboardName;
}
})
In DashboardsNAME.html
<div class="container" ng-Controller='DashboardsNAMEController'>Food</div>
This technique still requires that at some point before the route is instantiated you have registered DashboardsNAMEController
. I suspect that the best place to do it is in the module.run()
method with call to your own service but I do it in my main controller because it works and is a short controller anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With