Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

3 Answers 3

up vote 2 down vote accepted

Try with

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

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

share|improve this answer
    
Perfect thanks! I didn't realise I had to structure the URL differently, but it's not a problem. –  Coop Jul 27 '14 at 14:15

have your tried using it as a function instead?

$location.search();

share|improve this answer
    
Yes, that seems to return an empty object –  Coop Jul 27 '14 at 13:41
    
$location on it's own seems to work. Any idea why the search function would be returning empty? –  Coop Jul 27 '14 at 13:59
    
can you provide a plunker or a jsfiddle? It might be easier for us to find the problem. –  ryeballar Jul 27 '14 at 14:01

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.

share|improve this answer
    
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. –  Coop Jul 27 '14 at 13:45
    
@Cooper I updated the answer. :) –  Shrek Jul 27 '14 at 14:04
    
@Cooper no angular doesn't simply because angular routing is all after the hash and has no interest in location.search –  charlietfl Jul 27 '14 at 14:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.