angularjs和localStorage的变化事件 [英] angularjs and localStorage change event

查看:971
本文介绍了angularjs和localStorage的变化事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一些数据存储在localStorage的

I store some data in the localStorage

我想在我的应用程序angularjs是,当在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?

推荐答案

有一个角localStorage的模块:

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';
  }

};

在进一步的想你可能需要改变模块的setItem播出,因此如果localStorage的已经改变,你可以得到通知。也许叉,左右线50:

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
});

这是第二个选项的演示:
演示: http://beta.plnkr.co/lpAm6SZdm2oRBm4LoIi1

** **更新

我分叉的项目,并已在要使用该项目的事件包括在这里通知:的https://github.com/sbosell/angular-local-storage/blob/master/localStorageModule.js

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

我相信原来的图书馆接受了我的PR。我喜欢这个库的原因是它有一个cookie备份,以防浏览器不支持本地存储。

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.

这篇关于angularjs和localStorage的变化事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆