首页 > 解决方案 > 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()始终自动执行而无需任何刷新。

谁能解决我这个问题?

标签: angularjs

解决方案


使用存储事件:

 angular.element(window).on("storage", $scope.getAllContact);

 $scope.$on("$destroy", function() {
     angular.element(window).off("storage", $scope.getAllContact);
 });

有关信息,请参阅


推荐阅读