Angular ui router parse query params into booleans

前端 未结 2 1434
没有蜡笔的小新
没有蜡笔的小新 2021-01-13 07:22

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, fals

2条回答
  •  爱一瞬间的悲伤
    2021-01-13 07:46

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

    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.

提交回复
热议问题