2

I have a route set up in AngularJS, with a variable parameter.

This is an extension of this question; I can use params in a variable templateUrl like so:

.when('/course/:lesson', {
    templateUrl: function(params){
         return '/partials/course/' + params.lesson;
    }
    //...
})

However, if I try to do something for a variable controller name I get an unknown provider error

.when('/course/:lesson', {
    templateUrl: function(params){
         return '/partials/course/' + params.lesson;
    },
    controller: function(params){
         return params.lesson + 'Ctrl';
    }
})

Basically, instead of writing 100 different routes which all follow the exact same structure, I want to take whatever the lesson variable is and map it to the /partials/course/{{lesson}} route as well as the {{lesson}}Ctrl controller.

Is this possible?

Community
  • 1
  • 1
JVG
  • 20,198
  • 47
  • 132
  • 210

2 Answers2

3

You could do something like below, not cleaner one. But it will work

controller: function($scope, $controller, $routeParams){
     $controller($routeParams.lesson + 'Ctrl', {$scope: $scope});
}

Handling such situation will be easier, if you will look at ui.router, which has controllerProvider which will work like you were trying.

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
0

No - controllers name are static - they are functions, that are compiled before we start our app. More info here.

However, it is possible to dynamically add controller to view based of ngController. More info here

Community
  • 1
  • 1
uksz
  • 18,239
  • 30
  • 94
  • 161
  • 1
    Controller name is static however you can create you controller instance manually. Check Panraj's answer. – dfsq Apr 30 '16 at 07:33