使用“bool"的正确方法是什么?带有ui-router的参数类型? [英] What is the correct way to use the "bool" param type with ui-router?

查看:13
本文介绍了使用“bool"的正确方法是什么?带有ui-router的参数类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用 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({名称:'home.foo',url: '/foo/{isBar:bool}',控制器:函数(){},模板网址:'foo.html'});

我的期望是我应该能够像这样过渡到那个状态:​​

My expectation is that I should be able to transition to that state like this:

$state.go(home.foo, { isBar: false })

ui-sref="home.foo({ isBar: false })"

但是在生成的 $stateParams 中你会看到 isBar: true

however in the resulting $stateParams you will see isBar: true

查看bool"param 类型的编写方式 我想真/假应该在 url 上编码为 0/1,但这不会发生.如果在 $state.go 的参数中使用 0/1,那么它可以工作并被解码为 false/true,但为了进一步混淆这个问题,如果使用 ui-sref,这将不起作用.

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.

希望这个 plunker 能更好地解释它.任何提示表示赞赏!

Hopefully this plunker will explain it better. Any hints appreciated!

我使用 bool 参数类型的目标是在 $stateParams 中得到一个布尔数据类型

My goal in using the bool param type is to end up with a boolean data type in $stateParams

推荐答案

有一个 更新和工作 plunker 与 boolean 自定义类型

如果我们想使用类似 bool 的类型,期望并接受:

In case, we would like to work with a bool like type, which expects and accepts the:

truefalse0, 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/
    })

}]);

然后我们可以在任何状态中使用这个 url 定义:

And then we can use this url defintion inside of any state:

...
, url: '/foo/{isBar:boolean}'
...

注意:为什么是 boolean?不是bool?因为据我所知,bool 已经为 0|1 注册了

NOTE: why boolean? not bool? Because bool is already registered for 0|1 as far as I remember

检查它这里

原创

使用字符串"的简单解决方案在这个更新的插件中

simple solution working with "strings" in this updated plunker,

... // states definitions
, url: '/foo/{isBar:(?:bool|true|0|1)}'

这篇关于使用“bool"的正确方法是什么?带有ui-router的参数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆