I'm using AngularJD ui-router to capture my URL and send two parameters from that URL to my controller. Here are my requirements:
- The first parameter is a mandatory integer (
id
) - The second parameter is an optional string (
slug
) - The two parameters are separated by a
/
- I want it to ignore any single trailing
/
Currently, I'm doing this:
$stateProvider.state('mystate',
{
url: '/mystate/{id:int}{slug:(?:/[^/]+)?}',
params: {
slug: {value: null}
},
templateUrl: 'partials/mystate.html',
controller: function($stateParams) {
console.log('$stateParams.id=',$stateParams.id, ' $stateParams.slug=',$stateParams.slug);
}
}
For URL: mystate/1
This correctly captures:
$stateParams.id=1, $stateParams.slug=null
For URL: mystate/1/myslug
This captures the wrong value for slug
:
$stateParams.id=1, $stateParams.slug=/asdad
For URL: mystate/1/
This doesn't capture anything.
For URL: mystate/1/myslug/
This doesn't capture anything.
How can I write this so that it captures all four of the aforementioned URLs properly but doesn't pass any of the /
s to the controller?
For optional trailing slash, you need to set strict mode to false in a config block:
For having optional parameters, there's a long discussion here. At the end, they suggest using
squash
:squash
has good documentation, if you set it to true, it omits the parameter from URL when it has the default value.