Find new value of a variable in LocalStorage after returning to the view using $ state.go ();

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 entity variable value changes within the Controller Entities, 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. p>
{{ model.entity.name }}

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

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

    
asked by anonymous 29.04.2015 / 23:12

2 answers

1

Since you have not shown where the Entities controller is being used, I believe you may be in a state other than app.home .

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

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

With this, 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 the app.home state, is to use $state.reload() directly.

    
05.05.2015 / 14:55
0

The biggest issue is that you need to use $window instead of window .

$window.localStorage

Test with the example above.

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

    
12.06.2016 / 08:20