角UI路由器解析查询参数为布尔 [英] Angular ui router parse query params into booleans

查看:171
本文介绍了角UI路由器解析查询参数为布尔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑使用查询参数的状态这样的场景。我想有他们的声明为标志,所以我可以在控制器中,然后取出并获得真正未定义

Consider such scenario of a state with query parameters. I'd like to have them declared as flags so I can fetch then in the controller and get true, false or undefined

$stateProvider.state('foo.bar', {
         url: '/foobar?flag1&flag2',
         templateUrl: 'foo/bar/template.tpl.html',
         controller: 'FooBarCtrl'
});

myModule.controller('FooBarCtrl', function($stateParams){
         $stateParams.flag1 <<--- is string but can it be of type bool?
         $stateParams.flag2 <<--- is string but can it be of type bool?

});

一些URL例子:

Some URL examples:

/foobar?flag1=true    -->> should yield {flag1: true, flag2: undefined}
/foobar?flag2=false    -->> should yield {flag1: undefined, flag2: false}
/foobar?flag1=false&flag2=true    -->> should yield {flag1: false, flag2: true}
/foobar?flag1=1&flag2=0    -->> should yield {flag1: true, flag2: false}

etc...

目前$ stateParams仅提供字符串。有没有去使路由器解析PARAMS的标志?这将是比手动做解析控制器更优雅。

At the moment $stateParams delivers only strings. Is there away to make the router to parse the params as flags? That would be much more elegant than doing the parsing manually in the controller.

推荐答案

最终,以下为我工作:

    var stringToBoolean = function (s) {
        if (typeof s != 'string') {
            return undefined
        }

        if (/1|true|TRUE/.test(s)) {
            return true
        } else if (/0|false|FALSE/.test(s)) {
            return false
        } else {
            return undefined
        }
     };

     $stateProvider.state('foo.bar', {
                 url: '/foobar?{flag1}',
                 ...
                 onEnter: function ($stateParams) {
                        $stateParams.flag1 = stringToBoolean($stateParams.flag1);
                 }
      });

它不觉得超洁净,我宁愿有过这个功能集成到UI的路由器,但至少我能以这种方式来解决这个问题在美国的水平,没有污染我的控制器,与此逻辑。

It doesn't feel super clean, I'd rather to have had this functionality integrated into ui-router but at least I was able in this way to solve this in the level of the states, without polluting my controllers with this logic.

这篇关于角UI路由器解析查询参数为布尔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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