[英]How to watch for local storage change
在將此問題標記為重復之前,請注意我不使用$localstorage
的$localstorage
服務。
如何查看本地存儲更改?
我現在擁有的是:
var isUnlocked = window.localStorage.getItem('isUnlocked');
if(isUnlocked === "true") {
$scope.$apply(function () {
$scope.unlocked = true;
});
}
現在的問題是,在刷新可見之后,邏輯上的更改是第一個。 我怎么能改變這個?
使用$scope.$watch
,其函數返回您希望觀察的localStorage值。
function getValue(){
return window.localStorage.getItem('isUnlocked');
}
$scope.$watch(getValue, function(newValue){
if (newValue === "true"){
$scope.$apply(function(){ $scope.unlocked = true; });
}
});
您可以編寫一個包裝類,它在$ 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.