0

I am using $location.search to get the params from the url but it gives a null. My url is http://localhost/Site/?user=12345.

app.controller('UrlController', ['$scope', '$log','$location', function($scope,$log,$location) {

    var testsearch = $location.search();
    console.log(testsearch);

}]) 

I want to get the value 12345 for the user by parsing the url. How this can be achieved.

how can i parse the params from the url. I checked the documentation https://docs.angularjs.org/api/ng/service/$location

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
krishna_v
  • 1,501
  • 5
  • 30
  • 60

2 Answers2

2

You need to use $window

So:

var qstring = $window.location.search.substring(1);

The substring(1) just removes the ?

You can then use a function, like this one, to parse it into an object

String.prototype.parseQuerystring = function () {
    var query = {};
    var a = this.split('&');
    for (var i in a)
    {
        var b = a[i].split('=');
        query[decodeURIComponent(b[0])] = decodeURIComponent(b[1]);
    }

    return query;

}

And call it with:

var qParts = qString.parseQuerystring();

Issues with $location

There are some known issues with $location depending on HTML5 mode etc. Where $window doesn't have this issue. E.G https://github.com/angular/angular.js/issues/7239

Darren Wainwright
  • 30,247
  • 21
  • 76
  • 127
0

If you configure $location to use html5Mode (history.pushState), you need to specify the base URL for the application with a tag or configure $locationProvider to not require a base tag by passing a definition object with requireBase:false to $locationProvider.html5Mode():

  app.config(['$locationProvider', function($locationProvider) {
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    });
}]);

please refer https://docs.angularjs.org/error/$location/nobase

And for getting url parameter you can use belwo in your controller. you get parameter as a array in $location.search()

var urlParameter = $location.search(); console.log(urlParameter);