angularjs and localStorage change event

37,734

Solution 1

There is an angular localStorage module:

https://github.com/grevory/angular-local-storage

var DemoCtrl = function($scope, localStorageService) {

  localStorageService.clearAll();

  $scope.$watch('localStorageDemo', function(value){
    localStorageService.add('localStorageDemo',value);
    $scope.localStorageDemoValue = localStorageService.get('localStorageDemo');
  });

  $scope.storageType = 'Local storage';

  if (!localStorageService.isSupported()) {
    $scope.storageType = 'Cookie';
  }

};

After further thought you may need to change the module to broadcast on setItem so that you can get notified if the localStorage has been changed. Maybe fork and around line 50:

localStorage.setItem(prefix+key, value);
$rootScope.$broadcast('LocalStorageModule.notification.setItem',{key: prefix+key, newvalue: value});  // you could broadcast the old value if you want

or in the recent version of the library the casing was changed

$rootScope.$broadcast('LocalStorageModule.notification.setitem',{key: prefix+key, newvalue: value}); 

Then in your controller you can:

$scope.$on('LocalStorageModule.notification.setItem', function(event, parameters) {
   parameters.key;  // contains the key that changed
   parameters.newvalue;  // contains the new value
});

Here is a demo of the 2nd option: Demo: http://beta.plnkr.co/lpAm6SZdm2oRBm4LoIi1

** Updated **

I forked that project and have included the notifications here in the event you want to use this project: https://github.com/sbosell/angular-local-storage/blob/master/localStorageModule.js

I believe the original library accepted my PR. The reason I like this library is that it has a cookie backup in case the browser doesn't support local storage.

Solution 2

Incidentally, I've created yet another localStorage module for AngularJS which is called ngStorage:

https://github.com/gsklee/ngStorage

Usage is ultra simple:

JavaScript

$scope.$storage = $localStorage.$default({
    x: 42
});

HTML

<button ng-click="$storage.x = $storage.x + 1">{{$storage.x}}</button>

And every change is automagically sync'd - even changes happening in other browser tabs!

Check out the GitHub project page for more demos and examples ;)

Solution 3

I recently created a module allows you to simply bind a localStorage key to a $scope variable and also store Objects, Arrays, Booleans and more directly inside the localStorage.

Github localStorage Module

Solution 4

$scope.$on("LocalStorageModule.notification.setitem", function (key, newVal, type) {
      console.log("LocalStorageModule.notification.setitem", key, newVal, type);
    });

$scope.$on("LocalStorageModule.notification.removeitem", function (key, type) {
  console.log("LocalStorageModule.notification.removeitem", key, type);
});

$scope.$on("LocalStorageModule.notification.warning", function (warning) {
  console.log("LocalStorageModule.notification.warning", warning);
});

$scope.$on("LocalStorageModule.notification.error", function (errorMessage) {
  console.log("LocalStorageModule.notification.error", errorMessage);
});

this event calling when using https://github.com/grevory/angular-local-storage#getstoragetype

in app config

myApp.config(function (localStorageServiceProvider) {
  localStorageServiceProvider
    .setPrefix('myApp')
    .setStorageType('sessionStorage')
    .setNotify(true, true)
});
Share:
37,734

Related videos on Youtube

Li Song
Author by

Li Song

Updated on September 02, 2020

Comments

  • Li Song
    Li Song almost 4 years

    I store some data in the localStorage

    what I want in my angularjs app is that when the data in the localStorage changed, the app rerender the app, how can I do this?

    • lucuma
      lucuma about 11 years
      did one of these answers address your question?
  • Neil
    Neil about 11 years
    This is a good answer, Id like to see a jsfiddle to back it up for a +1
  • lucuma
    lucuma about 11 years
    Here you go the things we do for the +1's. Demo link posted to answer.
  • lucuma
    lucuma about 11 years
    I went ahead a forked the project and added the notifications.
  • Kosmetika
    Kosmetika almost 11 years
    yep, it's great stuff! much more easier
  • Stephen Kaiser
    Stephen Kaiser almost 11 years
    Nice implementation. Thanks!
  • Ulan Murzatayev
    Ulan Murzatayev over 9 years
    I see a problem with this solution. It will not catch the change event if the local storage variable was changed from the same app running in a different tab, or from inspector. Since these actions will not trigger broadcast.
  • lucuma
    lucuma over 9 years
    @UlanMurzatayev is that one of the requirements for the original question?
  • Ulan Murzatayev
    Ulan Murzatayev over 9 years
    @lucuma I think that is one of the requirements, since the author does not specify exactly how the data in localStorage is changed, so I assume that this case should be considered too.
  • lucuma
    lucuma over 9 years
    The answer was already accepted so I'll assume this solution worked for the OP. If you have a better answer that handles different browser tabs which might require polling the localstorage go for it!
  • Ulan Murzatayev
    Ulan Murzatayev over 9 years
    @lucuma please don't feel insulted. You did a great job. Probably that's my use case, and unfortunately, polling is the only option I can think of in this case.
  • lucuma
    lucuma over 9 years
    I wasn't insulted at all. Having multiple tabs open will almost undoubtedly require polling in some form in a spa type environment. Maybe write a new question to see what responses you get.
  • Walid Ammar
    Walid Ammar over 9 years
    the most awesome thing is even changes happening in other browser tabs!.
  • Maciej Gurban
    Maciej Gurban over 9 years
    Thank you for this addition to localStorage module. Really simplifies a lot of things.
  • ItJustWerks
    ItJustWerks about 9 years
    Is there a broadcast event on changes to localStorage though? I need one controller to bind on an object in localStorage that another controller is adding. If I create the binding too soon, the object doesn't exist and I get an error.
  • fubbe
    fubbe almost 9 years
    They changend 'LocalStorageModule.notification.setItem' to 'LocalStorageModule.notification.setitem' ----> lowercase "i" for item :) took me ages to figure that out !