Pass object as query string parameter
I would like to pass a search query string into a state. The url should look like this:
/goods?filters[paramA]=1&filters[paramB]=2
My state setting is as follows:
.state('goods', {
url: '/goods?filters',
โฆ
})
My link template looks like this:
<a ui-sref="goods({ filters: { paramA: 1, paramB: 2}})">Menu item label</a>
However ui-router does not encode it correctly and I get:
/goods?filters=[object Object]
How can I do it right?
source to share
To accomplish what you want, you need to use $ stateParams , not the query string you are trying to use. (although query strings can be used, it's easier to use $ stateParams)
First you need to assign / register stateful parameters:
$stateProvider
.state('someState', {
url: "/someLinkPath/:Param1",
templateUrl: 'stateHTML.html',
controller: function ($stateParams) {
console.log($stateParams);
}
});
Then you can construct a $ stateParams object and pass it into a reference to the state you want.
If you want a query string you need to flatten the added object into the string
You can use $ .param (jQuery):
var yourParams = $.param({ param1: Value1, param2: Value2 });
or write your own JS Vanilla function like this:
function toQueryString(obj) {
var parts = [];
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
parts.push(encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]));
}
}
return parts.join("&");
}
Edit: After thinking about your problem, I believe the problem is that you have objects wrapping around your parameters. When you use this:
<a ui-sref="goods({ filters: { paramA: 1, paramB: 2}})">Menu item label</a>
I think by doing this the ui-sref doesn't know how to handle the object (filter) with the sub-object. what you need to do is pass in one object, i think if you can change your code to only pass parameters as an object, your code will work.
<a ui-sref="goods({ paramA: 1, paramB: 2})">Menu item label</a>
source to share