Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most concise way to read query parameters in AngularJS?

I'd like to read the values of URL query parameters using AngularJS. I'm accessing the HTML with the following URL:

http://127.0.0.1:8080/test.html?target=bob

As expected, location.search is "?target=bob". For accessing the value of target, I've found various examples listed on the web, but none of them work in AngularJS 1.0.0rc10. In particular, the following are all undefined:

  • $location.search.target
  • $location.search['target']
  • $location.search()['target']

Anyone know what will work? (I'm using $location as a parameter to my controller)


Update:

I've posted a solution below, but I'm not entirely satisfied with it. The documentation at Developer Guide: Angular Services: Using $location states the following about $location:

When should I use $location?

Any time your application needs to react to a change in the current URL or if you want to change the current URL in the browser.

For my scenario, my page will be opened from an external webpage with a query parameter, so I'm not "reacting to a change in the current URL" per se. So maybe $location isn't the right tool for the job (for the ugly details, see my answer below). I've therefore changed the title of this question from "How to read query parameters in AngularJS using $location?" to "What's the most concise way to read query parameters in AngularJS?". Obviously I could just use javascript and regular expression to parse location.search, but going that low-level for something so basic really offends my programmer sensibilities.

So: is there a better way to use $location than I do in my answer, or is there a concise alternate?

like image 576
Ellis Whitehead Avatar asked Jun 16 '12 13:06

Ellis Whitehead


People also ask

Why we use query parameters in Angular?

Today we are building a simple navbar component to show the query parameters in the URL when navigated to. Query parameters are used to pass optional params to the Angular route.


1 Answers

You can inject $routeParams (requires ngRoute) into your controller. Here's an example from the docs:

// 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'} 

EDIT: You can also get and set query parameters with the $location service (available in ng), particularly its search method: $location.search().

$routeParams are less useful after the controller's initial load; $location.search() can be called anytime.

like image 160
Andrew Joslin Avatar answered Oct 18 '22 06:10

Andrew Joslin