Setting Multi level hash parameters using $location.search

1,713 views
Skip to first unread message

Anirvan Mandal

unread,
Apr 23, 2013, 6:38:29 AM4/23/13
to ang...@googlegroups.com
I have gone through the angularjs $location guide on how to use $location.search({a: 'b'}) for setting the query parameters for the current window location. 
It works fine for single level parameters. 

For Example $location.search({'bob': 'marley'}) == some/base/url/?bob=marley

The problem arises when I want to make a multi-level query parameters.

For example $location.search({'musician': {'bob': 'marley'}}) == some/base/url/?musician=%5Bobject%20Object%5D

Whereas I would want some thing like some/base/url/?musician%5Bbob%5D=marley

Is there something that I am doing wrong or is it an angular js bug?

If it is a bug then is there any other way to generate a multi level query parameters which has nested array and hashes?

Jeremy

unread,
May 21, 2013, 5:15:07 PM5/21/13
to ang...@googlegroups.com
There is a problem that urls are simple key/value pairs which is what Angular assumes when you pass an object. So for a nested object Angular just turns it into a string which is object [Object]. 

I have two possible solutions. First, avoid anything that isn't a key/value. This is probably just a good idea, but I realize sometimes you need to access those variables and parse them into array. Second format your values differently. You could do {'musician[bob]': 'marley'} or use a string and split them such as {musician: 'bob|marley'}. I prefer the later method when you live in a JS world, but I know servers often can accept a param like musician[key]=value and convert that to an array.

Nicholas Wright

unread,
Nov 28, 2014, 1:29:33 PM11/28/14
to ang...@googlegroups.com
If you're not concerned about the parameters of the query string being human readable then you can base64 encode the object using JavaScript's native btoa function, and then decode it the other end. For example:

Encoding:

    $location.search('a', btoa(angular.toJson(obj)));

Decoding:

    var search = $location.search();
    if (search.a) {
        var obj = angular.fromJson(atob(search.a));
    }
Reply all
Reply to author
Forward
0 new messages