Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

angularjs - What is the correct way to use the "bool" param type with ui-router?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)}'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...