【发布时间】:2015-09-13 20:32:30
【问题描述】:
我正在使用可以在这里找到的 ngStorage 模块:https://github.com/gsklee/ngStorage
我在 localStorage 中设置了 lastSeenId 用于实时更新社交订阅源,因为这是一个混合应用程序 (Laravel/AngularJS),我无法将其存储在 $scope 中。
我的StatusesController 在 X 秒内得到一个数组或数据(如果没有查看,则什么都没有),我得到数组的最后一项并像这样设置我的$localStorage var:
$localStorage.lastStatusSeen = lastId;
我的导航控制器是我为用户设置一些新计数器以查看他们是否错过任何内容的地方,我得到的 lastSeenId 是这样的:
$scope.$storage.lastStatusSeen 被发送到我的 API 以返回一些看不见的状态帖子。
这一切都有效,用户在状态页面上,如果有新数据,则将本地存储 var 设置为数据数组中的最后一个 ID。
问题是我的NavigationController 没有找到此更改,并且始终传递用户首次访问页面时传递的lastSeenId。
有没有办法在本地存储中观察该密钥的变化?
编辑:根据要求更新代码
app.controllers.navigationController = ['$scope', 'pollingService', '$localStorage', function($scope, pollingService, $localStorage) {
$scope.lastStatusSeen = $localStorage.lastStatusSeen;
$scope.$watch(function () {
return $localStorage.lastStatusSeen;
}, function (newVal, oldVal) {
if (!newVal) {
return;
}
if (newVal !== oldVal) {
// Assign to a local scoped var, or anything, here...
$scope.lastStatusSeen = newVal;
// I suggest call a method to do your logic outside this
//$scope.onIdChange(newVal, oldVal); // If you need oldVal
}
});
pollingService.startPolling('emailCount', 'api/email/new-count', 5000, function(response) {
$scope.emailCount = response.data;
});
pollingService.startPolling('statusCount', 'api/social/new-count?lastid=' + $scope.lastStatusSeen, 5000, function(response) {
$scope.socialCount = response.data;
});
}];
【问题讨论】:
标签: javascript angularjs angularjs-scope local-storage ng-storage