Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically loading the controller in angularjs $routeProvider

Tags:

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?

like image 319
Kia Panahi Rad Avatar asked Aug 24 '13 20:08

Kia Panahi Rad


2 Answers

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!

like image 151
Bradley Trager Avatar answered Oct 04 '22 19:10

Bradley Trager


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.

like image 26
Nathaniel Johnson Avatar answered Oct 04 '22 18:10

Nathaniel Johnson