gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 12:25:12 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com