How can I set a query parameter in AngularJS witho

2019-01-29 22:19发布

问题:

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?

回答1:

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