97

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?

Syscall
  • 19,327
  • 10
  • 37
  • 52
Ian Warburton
  • 15,170
  • 23
  • 107
  • 189
  • What Object do you get? Do you have a plunkr or a fiddle that demonstrates the issue that you face? You are correct when you use `$location.search()` but I wish to check the "object" that you get when you call it... – callmekatootie Jun 06 '13 at 14:24
  • I don't know what object it is. I tried enumerating the properties but there doesn't appear to be any. – Ian Warburton Jun 06 '13 at 14:39
  • Not sure how to do a fiddle that examines a query string. – Ian Warburton Jun 06 '13 at 14:43

10 Answers10

155

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

TheSharpieOne
  • 25,646
  • 9
  • 66
  • 78
  • 3
    As Naresh mentioned, `$locationProvider` also needs to be configured properly: https://code.angularjs.org/1.2.23/docs/guide/$location#-location-service-configuration (This tripped me up. Hopefully the link saves others some time.) – David Tchepak Aug 27 '14 at 00:53
  • 2
    To configure location provider, you need: window.app.config ['$locationProvider', ($locationProvider) -> $locationProvider.html5Mode true ] You also need a base tag in the HTML file: – Amin Ariana Jan 18 '15 at 20:57
  • Thanks for inspriation and useful tips, just share my case. I create a constant called userConfig and put everything inside, some settings can be overriden by query string for user flexibility. I use this and put the query in a globalController scope variable which is in HTML tag so any child controller can take the parameter including service. Because the userConfig is also put in the Service. So virtually, they can interact together. – 西門 正 Code Guy Nov 06 '15 at 14:56
  • I found it easier to just use a js function, $location.search() has to many moving parts. There are plenty of code examples out there for getting query string parameters. – nuander Jan 19 '17 at 20:50
  • @TheSharpieOne if you have a moment could you take a look at this question? http://stackoverflow.com/questions/43121888/where-to-capture-the-location-search-vars-in-the-run-statement-in-order-to-r – Leon Gaban Mar 30 '17 at 15:23
49

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

andersh
  • 8,105
  • 6
  • 39
  • 30
  • 11
    How is this not an answer? Maybe it is a bit short, but it _does_ seem to answer the question. – Léo Lam Feb 18 '15 at 22:47
  • If you check the timestamps, the answer was edited 2 hours after Dan's comment. It's really not that important, but i found it shocking that leo's comment was getting upvoted so i thought i'd point it out. – Bill Tarbell Jul 07 '15 at 12:05
41

$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);    
}]);
Vivek
  • 11,938
  • 19
  • 92
  • 127
alejandrociatti
  • 1,122
  • 11
  • 16
13

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

MasoodRehman
  • 715
  • 11
  • 20
10

you can use this as well

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

var queryValue = getParameterByName('test_user_bLzgB');
Rolwin Crasta
  • 4,219
  • 3
  • 35
  • 45
10

If your $location.search() is not working, then make sure you have the following:

1) html5Mode(true) is configured in app's module config

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

2) <base href="/"> is present in your HTML

<head>
  <base href="/">
  ...
</head>

References:

  1. base href="/"
  2. html5Mode
Community
  • 1
  • 1
Mahesh
  • 3,727
  • 1
  • 39
  • 49
7

Angular does not support this kind of query string.

The query part of the URL is supposed to be a &-separated sequence of key-value pairs, thus perfectly interpretable as an object.

There is no API at all to manage query strings that do not represent sets of key-value pairs.

rewritten
  • 16,280
  • 2
  • 47
  • 50
0

In my NodeJS example, I have an url "localhost:8080/Lists/list1.html?x1=y" that I want to traverse and acquire values.

In order to work with $location.search() to get x1=y, I have done a few things

  1. script source to angular-route.js
  2. Inject 'ngRoute' into your app module's dependencies
  3. Config your locationProvider
  4. Add the base tag for $location (if you don't, your search().x1 would return nothing or undefined. Or if the base tag has the wrong info, your browser would not be able to find your files inside script src that your .html needs. Always open page's view source to test your file locations!)
  5. invoke the location service (search())

my list1.js has

    var app = angular.module('NGApp', ['ngRoute']);  //dependencies : ngRoute
    app.config(function ($locationProvider) { //config your locationProvider
         $locationProvider.html5Mode(true).hashPrefix('');
    });

    app.controller('NGCtrl', function ($scope, datasvc, $location) {// inject your location service
        //var val = window.location.href.toString().split('=')[1];
        var val = $location.search().x1;    alert(val);
        $scope.xout = function () {
           datasvc.out(val)
           .then(function (data) {
              $scope.x1 = val;
              $scope.allMyStuffs = data.all;
           });
        };
        $scope.xout();
    });

and my list1.html has

<head>
    <base href=".">
    </head>
<body ng-controller="NGCtrl">
<div>A<input ng-model="x1"/><br/><textarea ng-model="allMyStuffs"/></div>
<script src="../js/jquery-2.1.4.min.js"></script>
<script src="../js/jquery-ui.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-route.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="../js/ui-bootstrap-tpls-0.14.3.min.js"></script>
<script src="list1.js"></script>
</body>

Guide: https://code.angularjs.org/1.2.23/docs/guide/$location

Jenna Leaf
  • 2,255
  • 21
  • 29
0

My fix is more simple, create a factory, and implement as one variable. For example

angular.module('myApp', [])

// This a searchCustom factory. Copy the factory and implement in the controller
.factory("searchCustom", function($http,$log){    
    return {
        valuesParams : function(params){
            paramsResult = [];
            params = params.replace('(', '').replace(')','').split("&");
            
            for(x in params){
                paramsKeyTmp = params[x].split("=");
                
                // Si el parametro esta disponible anexamos al vector paramResult
                if (paramsKeyTmp[1] !== '' && paramsKeyTmp[1] !== ' ' && 
                    paramsKeyTmp[1] !== null){          
                    
                    paramsResult.push(params[x]);
                }
            }
            
            return paramsResult;
        }
    }
})

.controller("SearchController", function($scope, $http,$routeParams,$log,searchCustom){
    $ctrl = this;
    
    var valueParams = searchCustom.valuesParams($routeParams.value);
    valueParams = valueParams.join('&');

    $http({
        method : "GET",
        url: webservice+"q?"+valueParams
    }).then( function successCallback(response){
        data = response.data;
        $scope.cantEncontrados = data.length; 
        $scope.dataSearch = data;
        
    } , function errorCallback(response){
        console.log(response.statusText);
    })
      
})
<html>
<head>
</head>
<body ng-app="myApp">
<div ng-controller="SearchController">
<form action="#" >
                          
                            
                            <input ng-model="param1" 
                                   placeholder="param1" />
                            
                            <input  ng-model="param2" 
                                    placeholder="param2"/>
                        
<!-- Implement in the html code 
(param1={{param1}}&param2={{param2}}) -> this is a one variable, the factory searchCustom split and restructure in the array params
-->          
                        <a href="#seach/(param1={{param1}}&param2={{param2}})">
                            <buttom ng-click="searchData()" >Busqueda</buttom>
                        </a>
                    </form> 
</div>
</body>
Ivan Fretes
  • 668
  • 7
  • 11
0

Very late answer :( but for someone who is in need, this works Angular js works too :) URLSearchParams Let's have a look at how we can use this new API to get values from the location!

// Assuming "?post=1234&action=edit"

var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?

post=1234&action=edit&active=1"

FYI: IE is not supported

use this function from instead of URLSearchParams

urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                      .exec(window.location.search);

    return (results !== null) ? results[1] || 0 : false;
}

console.log(urlParam('action')); //edit
Divek John
  • 623
  • 8
  • 16