I have been trying to make use of the param types with ui-router and can't seem to get them right.
$stateProvider.state({
name: 'home.foo',
url: '/foo/{isBar:bool}',
controller: function() { },
templateUrl: 'foo.html'
});
My expectation is that I should be able to transition to that state like this:
$state.go(home.foo, { isBar: false })
or
ui-sref="home.foo({ isBar: false })"
however in the resulting $stateParams you will see isBar: true
Looking at the way the 'bool' param type is written I suppose true/false should be encoded as 0/1 on the url but this doesn't happen. If use 0/1 in the params for $state.go then it works and is decoded as false/true but to further confuse the issue this doesn't work if using the ui-sref.
Hopefully this plunker will explain it better. Any hints appreciated!
Edit: My goal in using the bool param type is to end up with a boolean data type in $stateParams
There is an updated and working plunker with boolean
custom type
In case, we would like to work with a bool like type, which expects and accepts the:
true
,false
,0
,1
we just have to register our custom type:
app.config(['$urlMatcherFactoryProvider', function($urlMatcherFactory) {
$urlMatcherFactory.type('boolean',
// our type custom type
{
name : 'boolean',
decode: function(val) { return val == true ? true : val == "true" ? true : false },
encode: function(val) { return val ? 1 : 0; },
equals: function(a, b) { return this.is(a) && a === b; },
is: function(val) { return [true,false,0,1].indexOf(val) >= 0 },
pattern: /bool|true|0|1/
})
}]);
And then we can use this url defintion inside of any state:
...
, url: '/foo/{isBar:boolean}'
...
NOTE: why boolean
? not bool
? Because bool
is already registered for 0|1
as far as I remember
Check it here
ORIGINAL
simple solution working with "strings" in this updated plunker,
... // states definitions
, url: '/foo/{isBar:(?:bool|true|0|1)}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With