olivier
olivier

Reputation: 2645

How to watch for local storage change

Before you mark this question as duplicate, please note that I don't use the $localstorage service from angular.

How can I watch for a local storage change?

What i have now is this:

var isUnlocked = window.localStorage.getItem('isUnlocked');
      if(isUnlocked === "true") {
        $scope.$apply(function () {
        $scope.unlocked = true;
      });
      }

The problem right now is that the change is logically first after a refresh visible. How can I change this?

Upvotes: 1

Views: 4639

Answers (2)

kicken
kicken

Reputation: 2167

Use $scope.$watch with a function that returns the localStorage value you wish to observe.

function getValue(){
    return window.localStorage.getItem('isUnlocked');
}

$scope.$watch(getValue, function(newValue){
    if (newValue === "true"){
        $scope.$apply(function(){ $scope.unlocked = true; });
    }
});

Upvotes: 3

Pjetr
Pjetr

Reputation: 1382

You could write a wrapper-class, that sends an event on the $rootScope, and then listen for that event where an update needs to happen.

'use strict';

(function(angular) {
  angular
    .module('myModule')
    .service('StorageService', ['$rootScope', function($rootScope) {
      this.getItem = function(key) {
        return localStorage.getItem(key) || undefined;
      };
      this.setItem = function(key, value) {
        localStorage.setItem(key, value);
        $rootScope.$emit('STORAGE_SERVICE_' + key.toUpperCase() + '_UPDATED');
      }
    }]);
})(window.angular);

(function(angular) {
  angular
    .module('myModule')
    .controller('myController', ['$scope', 'StorageService', function($scope, StorageService) {
      $scope.$on('STORAGE_SERVICE_ISUNLOCKED_UPDATED', function() {
        var isUnlocked = StorageService.getItem('isUnlocked');
        if(isUnlocked === "true") {
          $scope.$apply(function () {
            $scope.unlocked = true;
          });
        }
      });
    }]);
})(window.angular);

Upvotes: 0

Related Questions