【问题标题】:Angularjs ngStorage watch localstorage variable in other controller/ browser tabAngularjs ngStorage 在其他控制器/浏览器选项卡中监视 localstorage 变量
【发布时间】:2015-06-21 11:07:09
【问题描述】:

我正在使用 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();
}

在另一个浏览器选项卡中修改本地存储值时如何观察/观察我的本地存储值?

【问题讨论】:

  • LocalStorage 上升特定事件,然后它的值发生了变化。您应该为此事件添加事件侦听器,而不是角度观察者。

标签: javascript angularjs local-storage


【解决方案1】:

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

每次更改本地存储时都会调用存储事件。

【讨论】:

【解决方案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); 
    });

}]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-13
    • 2015-09-07
    • 2014-08-13
    • 1970-01-01
    • 2017-12-03
    • 2011-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多