[英]How to watch for local storage change
Before you mark this question as duplicate, please note that I don't use the $localstorage
service from angular. 在将此问题标记为重复之前,请注意我不使用
$localstorage
的$localstorage
服务。
How can I watch for a local storage change? 如何查看本地存储更改?
What i have now is this: 我现在拥有的是:
var isUnlocked = window.localStorage.getItem('isUnlocked');
if(isUnlocked === "true") {
$scope.$apply(function () {
$scope.unlocked = true;
});
}
The problem right now is that the change is logically first after a refresh visible. 现在的问题是,在刷新可见之后,逻辑上的更改是第一个。 How can I change this?
我怎么能改变这个?
Use $scope.$watch
with a function that returns the localStorage value you wish to observe. 使用
$scope.$watch
,其函数返回您希望观察的localStorage值。
function getValue(){
return window.localStorage.getItem('isUnlocked');
}
$scope.$watch(getValue, function(newValue){
if (newValue === "true"){
$scope.$apply(function(){ $scope.unlocked = true; });
}
});
You could write a wrapper-class, that sends an event on the $rootScope, and then listen for that event where an update needs to happen. 您可以编写一个包装类,它在$ rootScope上发送一个事件,然后监听需要更新的事件。
'use strict';
(function(angular) {
angular
.module('myModule')
.service('StorageService', ['$rootScope', function($rootScope) {
this.getItem = function(key) {
return localStorage.getItem(key) || undefined;
};
this.setItem = function(key, value) {
localStorage.setItem(key, value);
$rootScope.$emit('STORAGE_SERVICE_' + key.toUpperCase() + '_UPDATED');
}
}]);
})(window.angular);
(function(angular) {
angular
.module('myModule')
.controller('myController', ['$scope', 'StorageService', function($scope, StorageService) {
$scope.$on('STORAGE_SERVICE_ISUNLOCKED_UPDATED', function() {
var isUnlocked = StorageService.getItem('isUnlocked');
if(isUnlocked === "true") {
$scope.$apply(function () {
$scope.unlocked = true;
});
}
});
}]);
})(window.angular);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.