Can angularjs routes have optional parameter values?

AngularjsAngularjs Routing

Angularjs Problem Overview


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.

Angularjs Solutions


Solution 1 - Angularjs

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

Solution 2 - Angularjs

Like @g-eorge mention, you can make it like this:

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

You can also make as much as u need optional parameters.

Solution 3 - Angularjs

Please see @jlareau answer here: https://stackoverflow.com/questions/11534710/angularjs-how-to-use-routeparams-in-generating-the-templateurl

You can use a function to generate the template string:

var app = angular.module('app',[]);

app.config(
    function($routeProvider) {
        $routeProvider.
            when('/', {templateUrl:'/home'}).
            when('/users/:user_id', 
                {   
                    controller:UserView, 
                    templateUrl: function(params){ return '/users/view/' + params.user_id;   }
                }
            ).
            otherwise({redirectTo:'/'});
    }
);

Solution 4 - Angularjs

Actually I think OZ_ may be somewhat correct.

If you have the route '/users/:userId' and navigate to '/users/' (note the trailing /), $routeParams in your controller should be an object containing userId: "" in 1.1.5. So no the paramater userId isn't completely ignored, but I think it's the best you're going to get.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexandru RView Question on Stackoverflow
Solution 1 - Angularjsg-eorgeView Answer on Stackoverflow
Solution 2 - AngularjszmilanView Answer on Stackoverflow
Solution 3 - AngularjschrisjordanmeView Answer on Stackoverflow
Solution 4 - AngularjsRoy DanielsView Answer on Stackoverflow