Angular ui router parse query params into booleans

前端 未结 2 1432
没有蜡笔的小新
没有蜡笔的小新 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:54

    You should be able to use the bool as a type

    url: '/foobar?{flag1:bool}&{flag2:bool}',
    

    But we can even use our custom type (let's call it boolean):

    app.config(['$urlMatcherFactoryProvider', function($urlMatcherFactory) {
      $urlMatcherFactory.type('boolean',
    {
     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/
    })
    }]);
    

    And the state def for url would be like this:

    url: '/foobar?{flag1:boolean}&{flag2:boolean}',
    

    and this should work:

    
    
    

    Here is plunker with example

提交回复
热议问题