0

Say I have a URL like this:

www.mysite.com?account=23&token=asdu756sdg65sdf

Now, I need to access those URL parameters individually using Angular JS.

I've tried using location.search inside my controller:

console.log(location.search);

Which nicely returns the full query string:

?account=23&token=asdu756sdg65sdf

But it seems to return a string, not an object. Is there an easy way to access the individual ids and values in the string?

I've also tried:

console.log($location.search());

Which seems to return an empty object.

3 Answers 3

2

Try with

var account = ($location.search()).account;

but the url should be like /#!/?account=1

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

1 Comment

Perfect thanks! I didn't realise I had to structure the URL differently, but it's not a problem.
0

have your tried using it as a function instead?

$location.search();

3 Comments

Yes, that seems to return an empty object
$location on it's own seems to work. Any idea why the search function would be returning empty?
can you provide a plunker or a jsfiddle? It might be easier for us to find the problem.
0

pure js way:

var getParamFromURL = function(_url) {
    var url = _url;
    var _paraString = url.indexOf("&") > -1 ? url.substring(url.indexOf("?") + 1, url.length).split("&") : url.substring(url.indexOf("?") + 1, url.length).split('');
    var _paraObj = {};
    for (i = 0; p = _paraString[i]; i++) {
        _paraObj[p.substring(0, p.indexOf("=")).toLowerCase()] = p.substring(p.indexOf("=") + 1, p.length);
    }
    return _paraObj;
}

via angular js:

 // Given:
 // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
 // Route: /Chapter/:chapterId/Section/:sectionId
 //
 // Then
 $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}

Great. @Cooper is right.

2 Comments

That looks like pure javascript to me. I'm pretty sure Angular JS has built in functions to do this job, and seeing as that's the framework I'm using for this project, I'd like to do it in that.
@Cooper no angular doesn't simply because angular routing is all after the hash and has no interest in location.search

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.