角UI路由器解析查询参数为布尔布尔、路由器、参数、UI

由网友(有诗意的七个字:且将心事兑入酒)分享简介:考虑使用查询参数的状态这样的场景。我想有他们的声明为标志,所以我可以在控制器中,然后取出并获得真正,假或未定义 Consider such scenario of a state with query parameters. I'd like to have them declared as flags so I c...

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

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.

阅读全文

相关推荐

最新文章