leoalmar
leoalmar

Reputation: 226

Angularjs reload values in LocalStorage variable when I come back to view

I have a view that use a LocalStorage Object 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 LocalStorage variable entity is changed in the EntitiesCtrl, but when the $state.go('app.home') show the Home view, the value wasn't changed in the

{{ model.entity.name }}

What can I do to take new value of window.localStorage['entity'] every time the $state.go('app.home'); is called?

Thanks!

Upvotes: 1

Views: 1512

Answers (2)

charlietfl
charlietfl

Reputation: 171669

I would change the service so it returns reference to an object. Then any changes made in any controller should update that same object prior to storing back in localStorage. You would then have prototypical inheritance binding across the app

.factory('EntityService', function (){
  var entity;  
  return {
    getEntity : function(){
      if(!entity){
          entity = JSON.parse(window.localStorage['entity'] || false);
       }
      return entity;// object stored in service now
    },
     saveEntity:function(){
         if(entity){
           window.localStorage['entity'] = JSON.stringify(entity);
        }                   
     }
  };
});

Then instead of updating localStorage directly, update the object and use save method in service

Upvotes: 1

floribon
floribon

Reputation: 19193

Instead of view-title="{{ model.entity.name }}">, try:

<ion-nav-title>{{model.entity.name}}</ion-nav-title>

I am not sure viewTitle supports angular interpolations.

Upvotes: 0

Related Questions