Search code examples
angularjsangularjs-routing

Can angularjs routes have optional parameter values?


Can I set a route with optional params (same template and controller, but some params should be ignored if they don't exist?

So instead of writing the following two rules, have only one?

module.config(['$routeProvider', function($routeProvider) {
    $routeProvider.
     when('/users/', {templateUrl: 'template.tpl.html', controller: myCtrl}).            
     when('/users/:userId', {templateUrl: 'template.tpl.html', controller: myCtrl})
}]);

Something like this ([this param is optional])

when('/users[/:userId]', {templateUrl: 'template.tpl.html', controller: myCtrl})
//note: this previous doesn't work

I couldn't find anything in their documentation.


Solution

  • It looks like Angular has support for this now.

    From the latest (v1.2.0) docs for $routeProvider.when(path, route):

    path can contain optional named groups with a question mark (:name?)