使用angularJS的localStorage - 如何动态地将值绑定到浏览器中的所有选项卡

时间:2016-10-31 14:42:47

标签: javascript angularjs html5

我有2个文件,index.html和server.js。

我使用localstorage在标签之间保存文字。我的代码如下。 2个问题: 1.如果我关闭浏览器(如果我将关闭计算机?),这将被保存吗? 2.如何将此代码更改为dymanic更改所有打开的选项卡中的值?目前,当我在旧标签上打开新标签/按下刷新时,它只是消除了新值...

由于

的index.html

<!DOCTYPE html>
<html ng-app="app">
<head>
    <script  src="http://code.angularjs.org/1.2.13/angular.js"></script>
    <script src="script.js"></script>
</head>
<body ng-controller="mainCtrl">
    <h1></h1>
    <h2>Current LocalStorage value is = {{ msg }} </h2>
    <input type="text" ng-model="value">
    <input type="button" value="save value" ng-click="update(value)">
</body>
</html>

的script.js

var app;
app = angular.module("app", []);
app.controller("mainCtrl", function(myLocalStorage, $scope) {

  $scope.msg = myLocalStorage.getData();

  $scope.update = function(msgContent) {
   $scope.msg = myLocalStorage.setData(msgContent);
 };

});
app.factory("myLocalStorage", function($window) {
  return {
    setData: function(val) {
      $window.localStorage && $window.localStorage.setItem('my-storage', val);
      return val;
    },
    getData: function() {
      return $window.localStorage && $window.localStorage.getItem('my-storage');
    }
  };
});

2 个答案:

答案 0 :(得分:2)

  1. 是。它会。
  2. 您应订阅存储更改事件

    $window.on('storage', this.onStorageChanged);
    

答案 1 :(得分:1)

正如有人已经回答:是的,即使关闭浏览器,本地存储也会保留其值。

另一个提示是使用ngStorage作为角度,以便您可以使用

$localStorage.setItem();

我建议您查看他们的文档,以便更轻松地进行本地/会话存储处理

根据回复编辑回答:

尝试添加一个类似的监听器:

$scope.$watch(function () {
   return $window.localStorage.getItem('my-storage');
}, function (newVal, oldVal) {
    if (!newVal) {
       return;
    }
    if (newVal !== oldVal) {
        $scope.update(newVal);  
        //$scope.onIdChange(newVal, oldVal); // If you need oldVal
    }        
});

如果您真的希望用户在同一个网站上打开多个浏览器,我不认为可以动态更改两个选项卡上的内容(这些视图相同)基于localStorage的。