Angular ui.router, Creating an Optional First Path

2020-03-30 01:59发布

问题:

Relatively new to working with Angular, but I couldn't seem to find any url aliasing or fully optional path params (something like {/var1}/:var2 when using ui.router's $stateProvider.

I'm looking to have the following both be valid paths, ideally on the same state declaration so that I can call state changes using one or both params.

/var1/var2
/var2

Naturally, I can use matches like the following, but none of these are true solutions.

  • /:var1/:var2, but this still requires an empty value for var1 (//var2)
  • /:var2?var1 or /:var2/:var1?, but neither of these are ideal in context as they rearrange the path.
  • /:var1/:var2 AND /:var2 as separate states, but I'd likely need to manage state changes more closely and select based on which params are available.

Any info to point me in the right direction would be greatly appreciated.

And a quick stripped down sample for context.

$stateProvider .state('app.view', { url : '/:var1/:var2' }).state('app.view2', { url : '/:var2' });

回答1:

Maybe this would work

.state('app.view', {
    url: '/:var1/:var2',
    templateUrl: 'yourTpl.html',
    controller: 'YourCtrl',
    params: {
        var1: {squash: true, value: null}
    }
})

squash configures how a default parameter value is represented in the URL when the current parameter value is the same as the default value