【发布时间】:2013-04-15 13:03:14
【问题描述】:
我在localStorage中存储了一些数据
我在我的 angularjs 应用程序中想要的是,当 localStorage 中的数据发生变化时,应用程序会重新呈现应用程序,我该怎么做?
【问题讨论】:
-
这些答案是否解决了您的问题?
标签: javascript angularjs local-storage
我在localStorage中存储了一些数据
我在我的 angularjs 应用程序中想要的是,当 localStorage 中的数据发生变化时,应用程序会重新呈现应用程序,我该怎么做?
【问题讨论】:
标签: javascript angularjs local-storage
有一个角度的localStorage模块:
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 已更改时收到通知。也许 fork 和第 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
或者在最新版本的库中,大小写已更改
$rootScope.$broadcast('LocalStorageModule.notification.setitem',{key: prefix+key, newvalue: value});
然后在你的控制器中你可以:
$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
我相信原始库接受了我的 PR。我喜欢这个库的原因是它有一个 cookie 备份,以防浏览器不支持本地存储。
【讨论】:
顺便说一句,我为 AngularJS 创建了另一个 localStorage 模块,称为 ngStorage:
https://github.com/gsklee/ngStorage
使用非常简单:
JavaScript
$scope.$storage = $localStorage.$default({
x: 42
});
HTML
<button ng-click="$storage.x = $storage.x + 1">{{$storage.x}}</button>
每个更改都会自动同步 - 即使更改发生在其他浏览器选项卡中!
查看 GitHub 项目页面以获取更多演示和示例;)
【讨论】:
even changes happening in other browser tabs!。
我最近创建了一个模块,让您可以简单地将 localStorage 键绑定到 $scope 变量,并将对象、数组、布尔值等直接存储在 localStorage 中。
【讨论】:
$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);
});
使用时调用此事件 https://github.com/grevory/angular-local-storage#getstoragetype
在应用配置中
myApp.config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setPrefix('myApp')
.setStorageType('sessionStorage')
.setNotify(true, true)
});
【讨论】: