Can angularjs routes have optional parameter values?

Alexandru R picture Alexandru R · Jul 7, 2013 · Viewed 144.4k times · Source

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.

Answer

g-eorge picture g-eorge · Oct 7, 2013

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?)