Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 783
Mike Pateras Avatar asked Jul 07 '13 14:07

Mike Pateras


People also ask

What is the difference between a query parameter and a route parameter?

The key difference between query parameters and route parameters is that route parameters are essential to determining route, whereas query parameters are optional.

How do I give a parameter query?

Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.

Can a query parameter be required?

Yes, mandatory parameters can be used in query parameters.

Can URI have query parameters?

It is very important to know when to use Query Parameter or URI Parameter while designing an API. URI parameter (Path Param) is basically used to identify a specific resource or resources whereas Query Parameter is used to sort/filter those resources.


1 Answers

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); 
like image 109
Stewie Avatar answered Sep 24 '22 01:09

Stewie