Fetch new value from a variable in Localstorage after returning to the view using $state.go();

Asked

Viewed 179 times

2

I have a view that uses a Localstorage variable called Entity.

/* Entity Service */ 
.factory('EntityService', function (){  
  return {
    getEntity : function(){
      return JSON.parse(window.localStorage['entity'] || false);
    }
  };
})

/* Route definition */
.state('app', {
  url: "/app",
  abstract: true,
  templateUrl: "templates/menu.html",
  controller: 'AppCtrl',
  resolve : {
    Entity : function(EntityService){
      return EntityService.getEntity();
    }
  }
})

/* AppCtrl*/
.controller('AppCtrl', function($scope,Entity) {
  $scope.model = {
   entity : Entity
  };
})

/* AppCtrl (view) */    
<ion-view view-title="{{ model.entity.name }}">
    <ion-content>
        <div class="padding">Home</div>
    </ion-content>
</ion-view>

/* EntitiesCtrl */
$scope.setEntity = function(entity){
  window.localStorage['entity'] = JSON.stringify(entity);
  $state.go('app.home');
}

/* EntitiesCtrl (view)*/
<div class="list">      
  <a class="item item-thumbnail-left" ng-click="setEntity(entity)" ng-repeat="entity in model.entities">
    <img src="img/entities/{{ entity.logo }}">
    <h2>{{ entity.name }} - {{ entity.acronym }}</h2>
    <p>{{ entity.city.name }} - {{ entity.city.state.acronym }}</p>
  </a>
</div>

The value of the variable Entity is changed within the Entities Controller, but when the $state.go('app.home') is called, the value of the variable is changed but the view continues with the old value of the variable.

{{ model.entity.name }}

When the $state.go('app.home') run, controller does not run again (checked with a console.log();).

What I need to do to make the controller search for the new variable value every time $state.go('app.home') is called?

2 answers

1


Since you haven’t shown where the Entities controller is being used, I believe you may be in a different state than app.home.

Therefore, I believe that what you want is the option reload of the method $state.go():

$state.go('app.home', null, {
    reload: true
});

With this, the controllers will be reloaded if they are already present in the current state/view.

Another way to do the same if you’re already in state app.home, is to use $state.reload() directly.

0

The bigger question is that you need to use the $window instead of window.

$window.localStorage

Test with the example above.

Use get,set and remove methods to manipulate data from localStorage.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.