Angularjs ngStorage在其他控制器/浏览器选项卡中监视localstorage变量

时间:2015-04-15 13:05:13

标签: javascript angularjs local-storage

我正在使用AngularJs和ngStorage制作购物车。我想将数据保存在本地存储中。当我从不同的浏览器选项卡中添加内容时,我想在购物车中打开购物车的http方法。我想使用$ scope。$ watch但它不起作用:(

我试图在localstorage中使用helper值,第一个控制器:

$scope.$watch('counter', function(newValue, oldValue) {
    if(newValue === oldValue){
      return;
    }
    console.log(newValue);
});

$scope.deleteItem = function (item) {
    var index = $scope.storage.products.indexOf(item);
    $scope.storage.products.splice(index, 1);
    $scope.counter = 0;
}

第二控制器:     $ scope.addToCart = function(code){

    var prod = {
        code: code,
        quantity: 1,
        color: 0,
        notes: '',
    };
    $scope.storage.products.push(prod);
    $scope.storage.counter=$scope.storage.counter+1;
    $scope.$apply();
}

如何在另一个浏览器选项卡中修改/观察我的localstorage值?

2 个答案:

答案 0 :(得分:2)

基于适用于您的上下文的@ stackg91引用:您可以将处理程序附加到本地存储,并在每次更改存储时广播事件:

var app = angular.module('app',['ngResource','ngRoute','ngCookies']);

app.config(['$routeProvider',function($routeProvider){
    $routeProvider
        .when('/', {templateUrl: '/home.html', controller: 'myCtrl'})
        .otherwise({ redirectTo: '/' });
}]).run(['$rootScope', function($rootScope) {
// you might need to inject you storage module here
    if (window.addEventListener) {
      window.addEventListener("storage", handler, false);
    } else {
      window.attachEvent("onstorage", handler);
    };

    function handler(e) {
   // get the value from storage based on storage module you're using
      $rootScope.$broadcast('counterChanged', 
localStorage.getItem('counter'));
    }
}]);

然后你可以在任何控制器中对这个事件作出反应:

app.controller('firstController',['$scope', function($scope){
    $scope.addToCart = function(code) {
        var prod = {
            code: code,
            quantity: 1,
            color: 0,
            notes: '',
        };
        $scope.storage.products.push(prod);
        $scope.storage.counter=$scope.storage.counter+1;
        $scope.$apply();
    }

}]);

app.controller('myCtrl',['$scope', function($scope){
    $scope.$on('counterChanged', function(event, data) { 
        // do things with the new counter
        console.log(data); 
    });

}]);

答案 1 :(得分:1)

试试这个https://truongtx.me/2014/06/16/cross-tab-communication-using-html5-dom-storage/ 与本地/会话存储的交叉表通信的相当不错的解释

每次更改Localstorage时,都会调用Storage事件。