angularjs 和 localStorage 更改事件 [英] angularjs and localStorage change event

查看:27
本文介绍了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?

推荐答案

有一个 angular 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

Here is a demo of the 2nd option: Demo: 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天全站免登陆