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

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

问题描述

考虑带有查询参数的状态的这种场景.我希望将它们声明为标志,以便我可以在控制器中获取然后获取 truefalseundefined

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?

});

一些网址示例:

/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 只提供字符串.是否可以让路由器将参数解析为标志?这比在控制器中手动解析要优雅得多.

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.

推荐答案

最终以下内容对我有用:

Eventually the following has worked for me:

    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-router 中,但至少我能够以这种方式在状态级别解决此问题,而不会因此而污染我的控制器逻辑.

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.

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

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