Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting values from query string in an URL using AngularJS $location

Regarding $location.search, the docs say,

Return search part (as object) of current url when called without any parameter.

In my URL, my query string has a param ?test_user_bLzgB without a value. Also $location.search() returns an object. How do I get the actual text?

like image 433
Ian Warburton Avatar asked Jun 06 '13 14:06

Ian Warburton


People also ask

Which method of $location service is used to get the URL without base prefix?

hash() Method: It is a read and writes method of $location service. It returns the current hash value of the current URL when called without parameters and when called with parameters it returns the$location object.

Can I pass URL as query parameter?

Yes, that's what you should be doing. encodeURIComponent is the correct way to encode a text value for putting in part of a query string. but when it is decoded at the server, the parameters of url are interpreted as seperate parameters and not as part of the single url parameter.


2 Answers

Not sure if it has changed since the accepted answer was accepted, but it is possible.

$location.search() will return an object of key-value pairs, the same pairs as the query string. A key that has no value is just stored in the object as true. In this case, the object would be:

{"test_user_bLzgB": true} 

You could access this value directly with $location.search().test_user_bLzgB

Example (with larger query string): http://fiddle.jshell.net/TheSharpieOne/yHv2p/4/show/?test_user_bLzgB&somethingElse&also&something=Somethingelse

Note: Due to hashes (as it will go to http://fiddle.jshell.net/#/url, which would create a new fiddle), this fiddle will not work in browsers that do not support js history (will not work in IE <10)

Edit:
As pointed out in the comments by @Naresh and @DavidTchepak, the $locationProvider also needs to be configured properly: https://code.angularjs.org/1.2.23/docs/guide/$location#-location-service-configuration

like image 137
TheSharpieOne Avatar answered Oct 12 '22 15:10

TheSharpieOne


If you just need to look at the query string as text, you can use: $window.location.search

like image 40
andersh Avatar answered Oct 12 '22 15:10

andersh