How can I set a query parameter in AngularJS without doing a route?

UrlAngularjsRoutingQuery Parameters

Url Problem Overview


My Angular app allows the user to load an item, and when that happens I'd like to set a query string that contains the item's Id so that if the user refreshes the page (or wants to link to it), the URL is already set (there's already code in place that loads the item if the Id is present in $routeParams).

How can I set that query parameter without causing a route? There are other things on the page that will get reset (including a plugin that will have to reload all of its data) if a route happens, so it's important that just the query parameter changes.

In short, when I load item 123, all I want to happen is that the URL changes from:

> www.myurl.com/#/Items

to:

> www.myurl.com/#/Items?id=123

without any routing taking place.

What's the best way to do this?

Url Solutions


Solution 1 - Url

In your $routeProvider configuration set reloadOnSearch to false:

$routeProvider
  .when('/items', {
    controller: 'ItemsCtrl',
    templateUrl: '/templates/items',
    reloadOnSearch: false
  },
  ...
);

and in your controller use $location.search() to set the id param:

$location.search('id', 123);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMike PaterasView Question on Stackoverflow
Solution 1 - UrlStewieView Answer on Stackoverflow