Angularjs ngStorage 在其他控制器/浏览器选项卡中查看本地存储变量

Angularjs ngStorage watch localstorage variable in other controller/ browser tab

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

我正在尝试在本地存储中使用辅助值,第一个控制器:

$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 = 函数(代码){

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

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

试试这个 https://truongtx.me/2014/06/16/cross-tab-communication-using-html5-dom-storage/ local/session storage

的交叉表通信的很好的解释

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

基于适合您的上下文的@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); 
    });

}]);