dynamically loading the controller in angularjs $routeProvider
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.
I have been attempting this same thing. One solution I've found is to do this inside your routeProvider:
$routeProvider .when("/Dashboards/:dashboardName",{ templateUrl:function(params) { return "Dashboards/" + params.dashboardName; }, controller: 'dynamicController' });
And then you do your calculation for what "pseudo-controller" (for lack of a better name) to load inside of the "dynamicController" definition.
var controllers = { unoController: function($scope, $routeParams, $rootScope) { // Do whatever }, dosController: function($scope, $routeParams, $rootScope) { // Whatever for this controller }}app.controller('dynamicController', ['$scope', '$routeParams', '$rootScope', function($scope, $routeParams, $rootScope) { controllers[$routeParams.dashboardName+"Controller"]($scope, $routeParams, $rootScope);}]);
This assumes that $routeParams.dashboardName is one of ["uno","dos"].
Take this with a grain of salt as I've only had about 3 days with Angular, but so far this approach has worked great for what I'm trying to accomplish.