AngularUI urlRouterProvider.when dynamic routing with optional parameters

Viewed 3553

I'm trying to create routes with optional parameters; apparently ui.route doesn't have that capability (even though ngRoute has since almost forever). So instead I have designated them as query parameters and am trying to translate them into a proper RESTful url that will be exploded for $stateParams:

In ngRouter syntax, I would specify: /:resource/:collection?/:type?/:index?

In ui.router, I've specified it as: /:resource?collection&type&index

And I've tried to translating it dynamically with a function that returns the path (tried both with a .when() and with a .rule()):

$urlRouterProvider
.when('' , '/index')
.when('/', '/index')
.when( urlMatcher.source , function convertToREST( $match , $stateParams )
{
    var params = [$match.resource];
    if ( angular.isDefined($match.collection) ) params[1] = $match.collection;
    if ( angular.isDefined($match.type) )       params[2] = $match.type;
    if ( angular.isDefined($match.index) )      params[3] = $match.index;
    var result = '/' + params.join('/');
    return result;
} )
.otherwise( '/404' );

The above causes no view to be rendered (remove the 3rd .when() and the view renders just fine).

And manually:

$urlRouterProvider
.when('' , '/index')
.when('/', '/index')
.when( '/:resource?collection' , '/:resource/:collection' )
.otherwise( '/404' );

This apparently causes circular iteration. I got this manual idea from the ui-router's sample app: state.js#L16. The only difference I see is that mine starts with a parameter, but I don't see what that matters.

1 Answers
Related