angularjs – refreshing child state view cause lose of data from the parent state

All we need is an easy explanation of the problem, so here it is.

I have the following ui-router states.

.state('admin.userView', {
  abstract:true,
  url:'/user/:id/',
  templateUrl:'./views/user/view.html',
  controller:'userViewController'
})

.state('admin.userView.home', {
  url:'',
  templateUrl:'./views/user/home.html',
  controller:'userHomeController'
})

I have fetched user details using http resource in userViewController to $scope.users.
When i move to the admin.userView.home state, I can access the $scope.users .
But when i refresh page with child state, the value in the $scope.users is lost.
How can i get the same.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Try moving that data into the resolve property of the admin.userView state declaration. Since you’re using nested resolves here you can then inject that resolved data into the admin.userView.home state declaration. Here’s an excerpt from the ui-router documentation.

$stateProvider.state('parent', {
      resolve:{
         resA:  function(){
            return {'value': 'A'};
         }
      },
      controller: function($scope, resA){
          $scope.resA = resA.value;
      }
   })
   .state('parent.child', {
      resolve:{
         resB: function(resA){
            return {'value': resA.value + 'B'};
         }
      },
      controller: function($scope, resA, resB){
          $scope.resA2 = resA.value;
          $scope.resB = resB.value;
      }

Source

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply