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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is great, I didn't know you could pass in $controller like this!
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

1 Comment

Controller name is static however you can create you controller instance manually. Check Panraj's answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.