Blejwi
Blejwi

Reputation: 1025

Angularjs ngStorage watch localstorage variable in other controller/ browser tab

I am using AngularJs and ngStorage to make a shopping cart. I want to keep data in local storage. When I add something from different browser tab I want to call my http method in the cart where cart is opened. I wanted to use $scope.$watch but it is not working :(

I was trying als to use helper value in localstorage, first 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;
}

Second Controller: $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();
}

How to observe/watch my localstorage value when it is modified in another browser tab?

Upvotes: 1

Views: 3376

Answers (2)

AndreiC
AndreiC

Reputation: 542

Based on @stackg91 references adapted to your context: you can attach a handler to local storage and broadcast an event every time the storage is changed:

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

Then you can react to this event in any controller:

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

}]);

Upvotes: 2

stackg91
stackg91

Reputation: 594

Try this https://truongtx.me/2014/06/16/cross-tab-communication-using-html5-dom-storage/ Pretty good explanation for cross-tab communication with local/session storage

Every time the Localstorage is changed the Storage event is called.

Upvotes: 1

Related Questions