how to pass querystring in angular routes?
Asked Answered
W

5

36

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;
        }]
    );
Woolworth answered 1/3, 2013 at 10:49 Comment(0)
S
26

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', ...)
Seif answered 1/3, 2013 at 16:2 Comment(1)
You only get part of truth here. routes do not work with query strings, becaouse query is not part of route. $location have nice method for query strings, and works just fine, as stated by JoshCincture
F
64

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.

Fontana answered 17/9, 2014 at 20:38 Comment(2)
Thanks for the answer. It's interesting that you can change the route using an anchor tag's href with a query string (as shown at the $route docs example) but not with the $location.pathHurley
Great answer. This would be a great example for the the official docs really, since it took me a bit to understand that get parameters weren't getting past routing.Tertius
S
26

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', ...)
Seif answered 1/3, 2013 at 16:2 Comment(1)
You only get part of truth here. routes do not work with query strings, becaouse query is not part of route. $location have nice method for query strings, and works just fine, as stated by JoshCincture
B
14

You could look at the search method in $location (docs). It allows you to add some keys/values to the URL.

For example, $location.search({"a":"b"}); will return this URL: http://www.example.com/base/path?a=b.

Boccherini answered 11/12, 2013 at 15:9 Comment(2)
Thanks! It would be great if you add an example of how to consume the a param inside the controller using $routeParamsImmanuel
@JossefHarush, Just use $location.search() to get the params.Vortical
L
2

use route params

var Ctrl = function($scope, $params) {
  if($params.filtered) {
    //make sure that the ID is there and use a different URL for the JSON data
  }
  else {
    //use the URL for JSON data that fetches all the data
  }
};

Ctrl.$inject = ['$scope', '$routeParams'];

http://docs.angularjs.org/api/ng.$routeParams

Leucocytosis answered 1/3, 2013 at 11:4 Comment(1)
I have to call two different functions in both the routes.. I have mentioned which function to call in their html files.. It is rendering albums.html well but not rendering album_images.html.. so its function is also not getting caledWoolworth
C
0

I can only think of two usecases for the querystring in URL:

1) If you need the key/value pair of your querystring in your controller (eg. to print Hello {{name}} and get the name in querystring such as ?name=John), then as Francios said just use $location.search and you will get the querystring as an object ({name:John}) which you can then use by putting it in scope or something (e.g. $scope.name = location.search().name;).

If you need to redirect to another page in your router based on what is given in the querystring, like (?page=Thatpage.htm) then create a redirectTo: in your routerProvider.when() and it will receive the search object as its third parameter. look at 2:10 of the following EggHead Video: http://www.thinkster.io/pick/SzcF8bGeVy/angularjs-redirectto

basically, redirectTo:function(routeParams,path, search){return search.page}

Carpenter answered 2/1, 2014 at 17:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.