javascript - Angularjs ngStorage 在其他 Controller /浏览器选项卡中观看本地存储变量

标签 javascript angularjs local-storage

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

我尝试在本地存储中使用辅助值,第一个 Controller :

$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;
}

第二个 Controller : $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();
}

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

最佳答案

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

然后你可以在任何 Controller 中对这个事件使用react:

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); 
    });

}]);

关于javascript - Angularjs ngStorage 在其他 Controller /浏览器选项卡中观看本地存储变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29651063/

相关文章:

Angularjs 过滤器匹配对象中的所有属性,即使我的表中只有一个属性

local-storage - 本地存储限制

javascript - 单击 react 中的元素时如何更改存储在 LocalStorage 中的数据?

javascript - 选择语言时使用自定义字体。

javascript - 无法在 AngularJS 的 Internet Explorer 11 中获取事件目标的父级

javascript - AngularJS 引用错误 : module is not defined

javascript - 如何查询外部域,将其存储在chrome扩展中,并调用它以在popup.html中显示?

javascript - 如何使 ViewComponent 与 Importmap-Rails 一起工作?

javascript - 将 Nan 更改为字符串

javascript - jQuery 兄弟选择器问题?