Prepend optional attribute in angular ui-router URL

后端 未结 3 1219
伪装坚强ぢ
伪装坚强ぢ 2020-12-04 02:12

Is there a way to have an optional attribute at the beginning of the url in ui-router? If so, how?

I want to achieve sth like this:

.state(\'events\'         


        
3条回答
  •  心在旅途
    2020-12-04 02:44

    I tried to answer the similar (if not same) here:

    Angular js - route-ui add default parmeter

    There is a working plunker, solving the issue for a language instead of for a city (but the concept is the same)

    so, we would/should introduce some super state 'root'.

    In our case, we can even use some regex to limit allowed values - because it would be hard to guess what is city and what is events

    .state('root', {
        url: '/{city:(?:Prague|Bristol|Denver)}',
        abstract: true,
        template: '
    ', params: {lang : { squash : true, value: 'Prague' }} })

    What is important here is the setting params : {}. It says, that the default value is 'Prague' - so that would be the city if none is selected. What is also important - it should be squashed, skipped if there is a match with 'Prague' param value:

    params: {lang : { squash : true, value: 'Prague' }}
    

    Now, we can introduce some nested state(s) which would declare 'root' as their parent:

    .state('events',{
        parent: 'root',
        url: '/events/:id'
        ...
    })
    

    Check the working example (with a language instead of city) here. For more details see the original Q & A

提交回复
热议问题