How to persist optional state parameter on browser back in ui-router? How to persist optional state parameter on browser back in ui-router? javascript javascript

How to persist optional state parameter on browser back in ui-router?


I would move the params definition to the parent state, so as to share the optional state params between your two child states.

The child states will inherit the $stateParams from your parent, as such there is no real 'workaround' needed.

Simply inject $stateParams as per usual in your child controllers and you will have full access to the params being passed around. If you don't want to utilise the params in a specific child state, simply avoid injecting them.

This works with;

  • Back button
  • Forward button
  • ui-sref (without params (will keep as-is))
  • ui-sref (with params (will overwrite))

$stateProvider  .state('parent', {    params: { p1: null, p2: null }  })  .state('parent.childOne', {    url: '/one',    controller: function ($stateParams) {      console.log($stateParams); // { p1: null, p2: null }    }  })  .state('parent.childTwo', {    url: '/two',    controller: function ($stateParams) {      console.log($stateParams); // { p1: null, p2: null }    }  })

If you at any point want to clear the params while travelling within the state tree of parent, you would have to do so manually.

That would be the only real caveat I can see by using this solution.

I realise manual clearing may not be desirable in the case you present, but you haven't taken an active stand against it, as such I feel the suggestion has merit.

updated plunker


One workaround solution is to cache the state params and conditionally load them when entering the tabs.account state. UI Router state config actually lets you provide an onEnter callback for these types of "do something on entering the state" situations.

Here's the basic logic using localStorage as the cache, with working Plunker here:

  • When you enter the tabs.account state, check for your state params
    • If you have them, cache them to local storage
    • If you don't, load them from local storage into $stateParams

Here's an example code snippet for reference (taken from the Plunker):

  $stateProvider.state('tabs.account', {    ...    onEnter: ['$stateParams', '$window', function($stateParams, $window) {      if($stateParams.param1) {        $window.localStorage.setItem('tabs.account.param1', $stateParams.param1);      } else {        $stateParams.param1 = $window.localStorage.getItem('tabs.account.param1');      }      if($stateParams.param2) {        $window.localStorage.setItem('tabs.account.param2', $stateParams.param2);      } else {        $stateParams.param2 = $window.localStorage.getItem('tabs.account.param2');      }    }],    ...  }