Option url path UI-Router

2019-06-07 01:28发布

问题:

In my angular application, I am making heavy use of nested states with UI-Router.

I am trying to create a parent state that determines the locale of the application based on a URL that has an optional locale path.

  • For Spanish www.website.com/es/search
  • For English www.website.com/search

the '/es' is required for Spanish, but English is implied by the parameter missing and I would prefer to not have the '/en'.

I want any child state of this one to inherit that locale value.

$stateProvider
    .state('localization', {
        abstract: true,
        url: '/:locale?',
        params: {
            locale: { value: 'en' }
        }
    })
    .state('search', {
        url: '/search',
        parent: 'localization'
    });

I'd like to be able to use $stateParams.locale in any of the child states.

回答1:

There is almost the same Q & A: Angular js - route-ui add default parmeter or another here

The solution is to create root state like this:

.state('localization', {
    url: '/{locale:(?:en|es|cs)}',
    abstract: true,
    template: '<div ui-view=""></div>',
    params: {locale : { squash : true, value: 'en' }}
})

Any child state then can just use this as a parent:

.state('home', {
    parent: 'localization', // parent will do the magic
    url: "/",
    ...
})
.state('activity', {
    parent: 'localization',
    ...

Check it here, where is also fully working plunker