Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs ui-router stateparams invisible loses on page refresh

Im working on a angular project, where i have set my states as shown below.

$stateProvider.state('UserPanel', {
    url: '/user',
    params: { userId: null },
    views: {
        'content@': {
            templateUrl: '/AngViews/UserPanel/UserPanel.UserDetails.html'
        }
    }
});

when i navigate to the view, it takes the params with it, so this part is working.

But when i update the page, it's loses the params. I know that if i defined the params in the url variable it will work. but i want to make it invisible.

I have found something like this, but don't know if it's gonna fix my problem. can't get it working if it does. anyone who can explain how this can be done?

Thanks for your time

like image 449
DaCh Avatar asked Sep 16 '15 07:09

DaCh


1 Answers

I faced the same problem and solved it with this code

angular.module('app').run(function($rootScope, $state, localStorageService) {

  $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
   var prefix = "stateParams.";
   var fromStateName = prefix + fromState.name;
   var toStateName = prefix + toState.name;
   var f = true;
   for (var k in toState.params) {
     f = f && (JSON.stringify(toParams[k]) == JSON.stringify(toState.params[k]));
   }
   if (f && localStorageService.get(toStateName) != null) {
     event.preventDefault();
     var savedToParams = localStorageService.get(toStateName); //retrieving toParams from local storage
     localStorageService.remove(toStateName);
     for (var k in toState.params) {
       toParams[k] = savedToParams[k]; //update only the params {} not url params
     }
     $state.transitionTo(toState,toParams);
   } else {
     var toSave = {};
     for (var k in toState.params) {
       toSave[k] = toParams[k]; //save only the params {} not url params
     }
     localStorageService.set(toStateName,toSave);
   }
  });

});

Gist

I try to use the localStorageService to 'cache' the params between state transitions.

when going from state A to state B , I remove the params previously stored for A.

I then check to see if the params that are being sent to B match the params in the state definition of B, and if they do match I load the params from the localStorage , because this means that the user has hit refresh and the params got reset.

I tested this code on a couple of cases , but it is still not fully tested.

like image 161
Ahmed Fahmy Avatar answered Oct 20 '22 09:10

Ahmed Fahmy