Pass complex object to ui-sref parameters

I need to create a url like this: / Filter list [status] = 1 &? Filter [type] = 2

I do:

link:

<a ui-sref="list({filter: {status: 1, type:2}})">List</a>

(pass a complex object to params, if you pass a simple object - {filter: 1} - this is normal, but I need it)

state:

 .state('list', { url: '/list?filter', … }) 

In general, I get url as:

 /list?filter=[object Object] 

Demo: http://plnkr.co/edit/wV3ieKyc5WGnjqw42p7y?p=preview

How can i fix this?

+7
javascript angularjs angular-ui-router
source share
1 answer

UI-Router comes with custom types support. There is an updated and working version of your plunker.

So, we can configure the def state as follows:

 app.config(function($stateProvider) { $stateProvider.state('list', { url: 'list?{filter:CoolParam}', 

As we can see, now the filter is of type CoolParam . Here we define it:

 app.config(['$urlMatcherFactoryProvider', function($urlMatcherFactory) { $urlMatcherFactory.type('CoolParam', { name : 'CoolParam', decode: function(val) { return typeof(val) ==="string" ? JSON.parse(val) : val;}, encode: function(val) { return JSON.stringify(val); }, equals: function(a, b) { return this.is(a) && this.is(b) && a.status === b.status && a.type == b.type }, is: function(val) { return angular.isObject(val) && "status" in val && "type" in val }, }) }]); 

And now {{$stateParams}} links like this:

 <a ui-sref="list({filter: {status: 1, type:2}})">Click me to see params</a> 

will return:

 {"filter":{"status":1,"type":2}} 

NOTE. In this case, I simplified my life and just turned json into a string. This means that the url encoded code will look like this:

 #/list?filter=%7B%22status%22:1,%22type%22:2%7D 

which {"status":1,"type":2}

But we can provide other ways to express our filter object.

Check here

Also linked are Q and A:

  • Angular ui router parsing request parameters in booleans
  • What is the correct way to use the "bool" parameter type with ui-router?

So, the above solution works fine with a filter like JSON. But in case we should have a url like this ?filter[status]=1&filter[type]=2 , we have to define the state differently. Each parameter must be declared as a separate simple type.

 $stateProvider.state('list2', { url: 'list2?state&type', }) 

But in this case we will have it as ?status=1&type=2 . This mapping is also part of this plunker .

+8
source share

All Articles