Angular ui router parsing request parameters in booleans

Consider this state scenario with query parameters. I would like them to be declared as flags, so I can get them 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? }); 

Some examples of URLs:

 /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... 

Currently, $ stateParams provides only strings. Is it possible to make a router for analyzing parameters like flags? This would be much more elegant than manual analysis in the controller.

+4
angularjs angular-ui-router
source share
2 answers

In the end, the following 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 seem super clean, I would prefer that this functionality be integrated into ui-router, but at least I was able to solve this problem at the state level in this way, without polluting my controllers with this logic.

+1
source share

You can use bool as a type

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

But we can even use our custom type (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 def state for url will be like this:

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

and this should work:

 <a ui-sref="foobar({ flag1: 0, flag2:true })"> <a ui-sref="foobar({ flag1: 1, flag2:false })"> 

Here is a plunker with an example

+7
source share

All Articles