how to pass querystring in angular routes?

Amb picture Amb · Mar 1, 2013 · Viewed 75.1k times · Source

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;
        }]
    );

Answer

Josh picture Josh · Sep 17, 2014

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.