Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: data binding between expressions and sessionstorage

Tags:

angularjs

I'm new to Angular. I have a single page application with a navbar which maps to some html "sections". Each section is visualized monitoring the state of a variable by the Angular directives ng-show.

After the first load all my sections are loaded and all HTML is in the browser. Now I can do some operations and save an object in sessionStorage. But the Angular expression referred to it does not load new data! I would like a classical data binding between my expression and my session storage. How can I do this?

Here there is a snippet of my html:

    <div class="container" ng-show="panels.isSelected(2)" ng-controller="DataController as pdc">
        {{pdc.myData.property_foo}}         
    </div>

and this is the controller to load data from sessionStorage

.controller('DataController', ['$window',  function($window) {

  pdc = this;

  //myData is an object
  pdc.myData = JSON.parse($window.sessionStorage.getItem("myData"));

}]);

Angular evaluates the value of myData only at the first loading of the page, instead of triggering a new evaluation of the expression each times myData changes...that's my problem...

Edit: I simulate my problem in this plnkr http://plnkr.co/edit/vG1IGOPsJlbUPOzYsY03?p=preview As you can see, when you press update the value displayed from session storage is not updated. You can see new values only by refreshing the page.

like image 481
floatingpurr Avatar asked Sep 27 '22 08:09

floatingpurr


1 Answers

You can pass a function to $scope.$watch to evaluate data that is not present on $scope. For instance, sessionStorage, this, SomeService or any data source really.

So, to do what you are asking you should inject $scope into your controller, set up a $watch for the return value of a function, and update this.myData to said value.

app.controller('DataController', ['$window',  '$scope', function($window, $scope) {

  pdc = this;

  $scope.$watch(function () {
    return $window.sessionStorage.getItem('myData');
  }, function (value) {
    pdc.myData = value;
  });

  pdc.update = function ( value ) {

    $window.sessionStorage.setItem("myData", value);

  };

}]);

Alternatively, you could reverse this (makes a little bit more sense in my opinion):

$scope.$watch(function () {
  return pdc.myData;
}, function (value) {
  $window.sessionStorage.setItem('myData', value);
});

pdc.update = function (value) {
  pdc.myData = value;
};

updated plunker

like image 151
Kasper Lewau Avatar answered Oct 04 '22 17:10

Kasper Lewau