Question

I am trying to retrieve GET parameters from the url of a page, using angularJS. I was able to retrieve them using the $location service, but this caused problems(see https://github.com/angular/angular.js/issues/4608). It appears this issue will be fixed at some point in 1.3.x, but I can't wait for a stable version that includes this fix.

So is there some other way I can retrieve GET parameters?


example:

url: mysite.com/shop/?id=1&size=2

I need to retrieve this:

{
  id: '1',
  size: '2'
}
Was it helpful?

Solution

I believe $location is somewhat of a proxy to the browser's location object (helps with testability among other things). If you don't want that dependency I would take the solution from How do I parse a URL query parameters, in Javascript? just write a service to do it for you:

var app = angular.module('myApp', []);

app.factory('myCustomLocation', [function(){

   return {
      search: function(){
          var query = location.search.substr(1);
          var data = query.split("&");
          var result = {};
          for(var i=0; i<data.length; i++) {
               var item = data[i].split("=");
               result[item[0]] = item[1];
          }
          return result;
      }
   }
}]);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top