Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

javascript - angularjs and localStorage change event

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...