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

First make the URL format correct for getting the query string use #?q=string that works for me

http://localhost/codeschool/index.php#?foo=abcd

Inject $location service into the controller

app.controller('MyController', [ '$location', function($location) { 

    var searchObject = $location.search();

    // $location.search(); reutrn object 
    // searchObject = { foo = 'abcd' };

    alert( searchObject.foo );

} ]);

So the out put should be abcd


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


$location.search() returns an object, consisting of the keys as variables and the values as its value. So: if you write your query string like this:

?user=test_user_bLzgB

You could easily get the text like so:

$location.search().user

If you wish not to use a key, value like ?foo=bar, I suggest using a hash #test_user_bLzgB ,

and calling

$location.hash()

would return 'test_user_bLzgB' which is the data you wish to retrieve.

Additional info:

If you used the query string method and you are getting an empty object with $location.search(), it is probably because Angular is using the hashbang strategy instead of the html5 one... To get it working, add this config to your module

yourModule.config(['$locationProvider', function($locationProvider){
    $locationProvider.html5Mode(true);    
}]);

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