Can I pass multiple controllers in $routeProvider.when() in angularJS?
Asked Answered
V

1

6

I tried searching for this on various threads, but I can't conclusively understand this.

test.config(['$routeProvider', function($routeProvider){
$routeProvider
    .when('/',
        {
            controller:'SimpleController1',
            templateUrl: 'partials/1.html'
        })
    .when('/xyz',
        {
            controller:'SimpleController1, SimpleController2',
            templateUrl:'partials/2.html'
        })
    .otherwise({ redirectTo: '/'});
}]);

I tried doing the above snippet, but it's not working. Can I do something like this? If yes, then what is it that I'm doing wrong here?

Vang answered 31/7, 2014 at 14:29 Comment(2)
whats the requirement, what do you need that??Notarize
I want to get an ajax response from a second controller based on an item from first controller's response.Vang
M
13

Only one controller is allowed and will be assigned to the loading template as the controller in ng-view. No need to define ng-controller in the template for a main controller.

If you need to define multiple controllers I suggest you define one main/parent controller and use that in the routeProvider and then have others already in the template using the ng-controller directive.

or...

Check into using Angular UI's UI-Router : http://angular-ui.github.io/ which is a much more versatile router.

Mcmullan answered 31/7, 2014 at 14:47 Comment(3)
This is the right answer, but I'd also recommend directives, as directives can have a controller attached to them as well. Repeatable elements in particular can benefit from being setup as directives.Gotland
I figured out UI-Router enough to get started, but I still can't think of a way except creating a parent controller to pass multiple controllers.Vang
Your last sentence implies you can do this with UI-Router, but I'm guessing, more subtly you don't have to with UI-Router. Which is it?Dharna

© 2022 - 2024 — McMap. All rights reserved.