Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set URL query parameters without state change using Angular ui-router

How should I update the address bar URL with a changing query parameter using AngularJS' ui-router to maintain state when refreshing the page?

Currently, I am using $state.transitionTo('search', {q: 'updated search term'}) whenever input changes, but the problem is that this reloads the controller, redraws the window and loses any text input focus.

Is there a way to update stateParams and sync it to the window URL?

like image 299
Petrus Theron Avatar asked Jan 02 '14 13:01

Petrus Theron


2 Answers

I was having trouble with .transitionTo until I updated to ui-router 0.2.14. 0.2.14 properly changes the location bar (without reloading the controller) using a call like this:

$state.transitionTo('search', {q: 'updated search term'}, { notify: false }); 
like image 186
pmont Avatar answered Sep 23 '22 00:09

pmont


edit: Played around with this some more today, and realized that angular ui-router has a similar option as the native routerProvider: "reloadOnSearch".

https://github.com/angular-ui/ui-router/wiki/Quick-Reference#options-1

It's set to true by default, but if you set it to false on your state, then the state change won't happen when the query parameters are changed. You can then call $location.search(params); or $location.search('param', value); and the URL will change, but ui-router won't re-build the entire controller/view. You'll probably also need to listen for the $locationChangeStart event on the root scope to handle back and forward history actions within your app, as these also won't cause state changes.

I'm also listening for the $stateChangeSuccess event on my controller's scope to capture the initial load of the page/route.

There is some discussion on github for using this feature with path changes (not just URL changes): https://github.com/angular-ui/ui-router/issues/125 but I haven't tested that at all since my use case was specific to query string parameters.

The previous version of my answer mentioned this github issue:

https://github.com/angular-ui/ui-router/issues/562

But that's a slightly separate issue, specifically showing a modal of one state over another state without the non-modal state changing. I tried the patch in that issue, but it's clear that it isn't meant for preventing the entire state from reloading on URL change.

like image 37
Jay Klehr Avatar answered Sep 21 '22 00:09

Jay Klehr