angularjs - AngularJS在localStorage中获取新数据时调用方法
问题描述
我正在使用 angularJS localstorage,我很好地注入了这个但是代码中的问题。
我想当 localstorage 获取新数据时,它会$scope.getAllContact()
自动调用一个函数。
我正在尝试解决这个问题,例如,我在浏览器中打开了两个选项卡,如果我在一个选项卡中更改任何内容,最新的更改也应该反映在其他选项卡中,而无需重新加载和刷新。
首先看我的代码:
app.controller('crudCtrl', function($scope, $http, $timeout, $localStorage, $sessionStorage) {
$scope.getAllContact = function() {
var data = $http.get("http://127.0.0.1:8000/api/v1/contact/")
.then(function(response) {
$scope.contacts = response.data;
// show something if success
}, function(response) {
//show something error
});
};
$scope.getAllContact();
// below method will post data
$scope.formModel = {};
$scope.onSubmit = function () {
$http.post('http://127.0.0.1:8000/api/v1/contact/', $scope.formModel)
.then(function(response) {
$localStorage.name = response.data;
$timeout(function() {
$scope.successPost = '';
}, 4000);
//below $scope will push data in client site if the request is success
$scope.contacts.push(response.data);
//if any error occurs, below function will execute
}, function(response) {
// do nothing for now
});
};
});
上面在$scope.onSubmit()
methond中,我也将提交的数据发送到localstorage,所以我需要如果localstorage获取新数据,它应该$scope.getAllContact()
始终自动执行而无需任何刷新。
谁能解决我这个问题?
解决方案
使用存储事件:
angular.element(window).on("storage", $scope.getAllContact);
$scope.$on("$destroy", function() {
angular.element(window).off("storage", $scope.getAllContact);
});
有关信息,请参阅
推荐阅读
- android - Android SDK版本升级
- google-cloud-dataflow - 为什么要选择许多较小的机器类型而不是较少的大型机器类型?
- android - 将 PreferenceDataStore 与 Firebase 数据库一起使用
- javascript - 如何在这个 PHP --> HTML --> JS 代码中将字符串值传递给 JS 函数?
- java - Maven and installing a command-line program
- powershell - 从另一个使用命名参数和路径中的空格调用一个 powershell 脚本
- awk - 按小时计算列中的值并添加标题
- .net-core - 已发布的自包含 dotnet 核心应用程序的运行时要求
- c# - WPF 应用程序中所有窗口的相同菜单栏或工具栏
- neo4j - 在 Neo4j 中寻找 K 最短路径