Generally, AngularJS does make it straightforward to analyze query parameters. However, getting there is not so obvious. Here are some hurdles that I recently overcame when researching and implementing.
You must put your module in ‘HTML5 mode’.
Code can look something like this:
app.config( [ '$locationProvider', function( $locationProvider ) {
// In order to get the query string from the // $location object, it must be in HTML5 mode. $locationProvider.html5Mode( true ); }]);
You must add a ‘base’ element to your HTML.
If you do not add this line, you will get a ‘nobase’ error in the console. The link looks it can go anywhere in your markup:
<!-- This line is necessary to support $location HTML5 mode (for query string parameters). --> <base href="/">
You must inject $location into your Controller.
It’s easy to forget because there are two locations (like all injections):
app.controller( 'MyController', [ '$scope', '$location', function( $scope, $location ) { etc..
Check if the query parameter exists before trying to use it.
Since AngularJS provides the query string as a set of key/value pairs, use something like this:
// Example - http://my.site.com/?myparam=33 if ( $location.search().hasOwnProperty( 'myparam' ) ) { var myvalue = $location.search()['myparam']; // 'myvalue' now stores '33' }