Search code examples
javascriptangularjsurl-routingngrouteangularjs-ng-route

How to set accepted values for angular route parameter?


I have to make two types of url: /:culture and /:author, where both have first-level url parameters. While culture is set of predefined parameters like en, es, en-us, br, fr, it, etc., author could be any username from db (except the names of cultures). So I wanna make the routing that could send user to HomeCtrl when param is in set of cultures and if not it would send him to AuthorCtrl. What could I do?

.when('/:culture/', {
    templateUrl:'partials/home/home',
    controller:'vvHomeCtrl'
});

Solution

  • You can define templateUrl and controller as functions and make this route like:

    .when('/:cultureOrAuthor/', {
        templateUrl: function(params) {
            // AVAILABLE_CULTURES is your predefined array
            if(AVAILABLE_CULTURES.indexOf(params['cultureOrAuthor'])!==-1) {
                return 'urlForCultures';
            } else {
                return 'urlForAuthors';
            }
        },
        controller: function($scope, $routeParams) {
            if(AVAILABLE_CULTURES.indexOf($routeParams['cultureOrAuthor'])!==-1) {
                // first logic
            } else {
                // second logic
            }
        }
    });
    

    This is a good solution for simple controllers. Otherwise consider using resolve from router (docs).