-2

What is the correct Angular approach to retrieving the URL parameters?

Example: http://example.com/mypage.html?product=1234&region=4&lang=en

Thanks

3 Answers 3

1

This will convert your query into an object

var queryData = url.split('?')[url.split('?').length - 1].split('&').reduce(function(prev, curr){
    var fieldName = curr.split('=')[0]; 
    var value = curr.split('=').length > 1 ? curr.split('=')[1] : '';
    prev[fieldName] = value; 
    return prev
}, {});

And then you can access them by queryData.product, for example. Not angular, but it's a solution.

For the angular way, you can use $location.search() as described here http://www.angulartutorial.net/2015/04/get-url-parameter-using-angular-js.html

Sign up to request clarification or add additional context in comments.

2 Comments

Hi @TitusPopovici. Same question as well. This, only seems to work if my URL ends with #/ as in example.com/mypage.html#/?product=1234&region=4&lang=en. Do you know if there is a workaround for this? The latter does not feel like a typical URL.
Not that I am aware of, for the angular way. You could make your own angular service that uses the function I wrote above for url's that are not angular routes (with the #/)
1

You can use the $location service. For example:

angular.module('parameters', []).run(['$location',
  function($location) {
    var params = $location.search();
  }
]);

4 Comments

Thanks @roger. This only seems to work if my URL ends with #/ as in example.com/mypage.html#/?product=1234&region=4&lang=en. Is there any workaround for this?
Are you usinge html5Mode? Because that your URL doesn't have the prefix "#/"? "$location.search();" works on html5Mode on the same way. If not, your parameters always have to be after "#/" prefix, this is the angular way, your URL will always be completed with "#/".
Thanks @roger. I read about html5mode, and even saw the documentation, but I'm super confused on how to implement this. It says to use $locationProvider, but where do I set this? Would it be in the controller? Because I would need it to take effect globally
You should use the config function of your module (angular.module('parameters', []).config(...))
0

I posted the same question with more details, and found a perfect response. Please see DavidL's response in my question here:

Reading URL parameters in AngularJS - A simple way?

Thanks to everyone who assisted me in this thread; perhaps I didn't include enough details in the original question.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.