我将一些数据存储在localStorage
中 在我的angularjs应用程序中我想要的是,当localStorage中的数据发生变化时,应用程序会重新呈现应用程序,我该怎么做?答案 0 :(得分:29)
有一个有角度的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已更改时收到通知。也许叉子和第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
我相信原来的图书馆接受了我的公关。我喜欢这个库的原因是它有一个cookie备份,以防浏览器不支持本地存储。
答案 1 :(得分:26)
顺便提一下,我为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项目页面以获取更多演示和示例;)
答案 2 :(得分:5)
我最近创建了一个模块,允许您简单地将localStorage键绑定到$ scope变量,还可以直接在localStorage中存储Objects,Arrays,Booleans等。
答案 3 :(得分:1)
$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)
});