Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass querystring in angular routes?

I am working with AngularJS routes, and am trying to see how to work with query strings (for example, url.com?key=value). Angular doesn't understand the route which contains key-value pair for the same name albums:

angular.module('myApp', ['myApp.directives', 'myApp.services']).config(         ['$routeProvider', function($routeProvider) {             $routeProvider.             when('/albums', {templateUrl: 'albums.html', controller: albumsCtrl}).             when('/albums?:album_id', {templateUrl: 'album_images.html', controller: albumsCtrl}).             otherwise({redirectTo: '/home'});         }],         ['$locationProvider', function($locationProvider) {             $locationProvider.html5Mode = true;         }]     ); 
like image 359
Amb Avatar asked Mar 01 '13 10:03

Amb


2 Answers

It is correct that routes do not work with query strings, however that doesn't mean you can't use query strings to pass data between pages when switching routes! The glaring limitation with route parameters is that they can't be updated without reloading the page. Sometimes this isn't desired, for instance after saving a new record. The original route parameter was a 0 (to signify a new record), and now you want to update it with the correct ID returned through ajax so that if the user refreshes the page they see their newly saved record. There is no way to do this with route parameters, but this can be accomplished by using query strings instead.

The secret is not to include the query string when changing the route, because that will cause it not to match the route template. What you can do is change the route and then apply the query string parameters. Basically

$location.path('/RouteTemplateName').search('queryStringKey', value).search( ... 

The beauty here is that the $routeParams service treats query string values identically to real route parameters, so you won't even have to update your code to handle them differently. Now you can update the parameters without reloading the page by including reloadOnSearch: false in your route definition.

like image 116
Josh Avatar answered Sep 22 '22 17:09

Josh


I don't think routes work with query strings. Instead of url.com?key=value can you use a more RESTful URL like url.com/key/value? Then you would define your routes as follows:

.when('/albums', ...) .when('/albums/id/:album_id', ...) 

or maybe

.when('/albums', ...) .when('/albums/:album_id', ...) 
like image 40
Mark Rajcok Avatar answered Sep 25 '22 17:09

Mark Rajcok