0
votes

I am trying to have dynamic routing in Angular 1.3. Something similar to what it described here and here. The examples suggest something like this:

$routeProvider.when('/:group/:pagename', {
    controller: 'RouteCtrl',
    templateUrl: 'uirouter.html'
})

and then the controller will have access to group and pagename through $routeParams. That works

I am trying to make this routing a little more dynamic and have template and controller to be selected dynamically as well:

$routeProvider.when('/:group/:pagename', {
    controller: $routeParams.group + 'Ctrl',
    templateUrl: $routeParams.pagename + '.html'
})

When I put a breakpoint on when I can see that there is $get property with a function that has $routeParams as one of parameters. But I can't figure out how to retrieve its values.

The project is in very early stage - I can go with ui-router or with ng-router if any of them has this functionality.

2

2 Answers

2
votes

For the dynamic templateUrl portion you could try:

$routeProvider.when('/:group/:pagename', {
    controller: "SomeCtrl",
    templateUrl: function(params){return params.pagename + '.html';}
})

Not sure if the same could be done with the controller however.

2
votes

Instead of a direct value you can declare a function that will return a templateUrl string, i.e.:

$routeProvider.when('/:group/:pagename', {
    controller: $routeParams.group + 'Ctrl',
    templateUrl: function (routeParams) {
        return routeParams.pagename + '.html';
    }
});

I guess the same may be true for controller, but you have to test that one out, as I've never used it for controllers.

That being said, if you have so much dynamic logic in this place, maybe instead of treating this as different controllers, you could encapsulate those views as different directives and the ng-if certain directive depending on $routeParams which will be set in one wrapping controller?