3

I want to have an optional url segment for the following example:

url: "/post/:category/:subcategory/:title/{id:int}",

In the above example subcategory is optional. For example it will accept:

url: "/post/sports/football/some-title/10",

and it will also accept:

url: "/post/sports/some-title/15",

which do not have subcategory. I can do that using to separate states but is there any rule for that? Please note only subcategory segment is optional. Others are mandatory.

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
im_tsm
  • 1,965
  • 17
  • 29

2 Answers2

4

.state('post', { url: '/post/:category/:subcategory/:title/:{id:int}', templateUrl: 'views/post.html', controller: 'postCtrl', params: { subcategory: { squash: true, value: null }, } })

For more info read the doc

nmanikiran
  • 2,866
  • 15
  • 19
2

Solution is in detail described here

Angular js - route-ui add default parmeter

and here is how we can define such parameter:

.state('state', {
    url: '/:category/{subcategory:(?:football|tennis|hokey)}/:title/:id',
    abstract: true,
    template: '<div ui-view=""></div>',
    params: {subcategory : { squash : true, value: 'football' }}
})
Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • Can you explain this part `(?:football|tennis|hokey)` ? Actually subcategory can be a long list. – im_tsm Sep 05 '16 at 12:26
  • that is the regular expression, the set of subcategory known values. That will help UI-Router to understand, if in this part `/post/sports/some-title/` is *some-title* subcategory or just another parameter... Other words, without that (it is really essential part) UI-Router could hardly decide... if it is subcategory or not. So we would need something like that ;) – Radim Köhler Sep 05 '16 at 12:29
  • Okay, actually I don't care other values except id. Anyways, thanks for your reply. – im_tsm Sep 05 '16 at 12:32
  • yes I understand your point, but as I said subcategory can be a large list and may be dynamically added to database. – im_tsm Sep 05 '16 at 12:34