【问题标题】:localStorage with angularJS - how to dynamic bind value to all tabs in browserslocalStorage 与 angularJS - 如何将值动态绑定到浏览器中的所有选项卡
【发布时间】:2017-03-13 16:09:43
【问题描述】:

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

我正在使用 localstorage 在选项卡之间保存文本。我的代码如下。 2个问题: 1. 如果我关闭浏览器(如果我将关闭计算机?),这是否会被保存。 2.如何更改此代码以动态更改所有打开选项卡中的值?目前它只是在我打开新标签/按旧标签刷新时显示新值...

谢谢

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

【问题讨论】:

    标签: javascript angularjs html


    【解决方案1】:
    1. 是的。会的。
    2. 您应该订阅存储更改事件

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

    【讨论】:

    • 谢谢..我把这条线放在哪里,它有什么作用?
    【解决方案2】:

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

    另一个技巧是使用ngStorage for angular,这样你就可以使用

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

    如果您真的希望用户打开同一个网站的多个浏览器选项卡,我认为不可能根据本地存储动态更改两个选项卡上的内容(它们是相同的视图)。

    【讨论】:

    • 谢谢你..我想要完成的是一种在所有打开的选项卡之间动态绑定我的存储的方法..意味着一旦我在一个选项卡中更改 txt..所有其他 txt 会发生什么在其他选项卡中?你明白了......它们会自动更新......类似于: $window.on('storage', this.onStorageChanged) e 上面的人建议......但是我应该把这行放在我的代码中的哪里?正确的语法是什么?
    猜你喜欢
    • 2013-05-09
    • 1970-01-01
    • 2011-06-07
    • 2015-06-21
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    • 2021-01-23
    相关资源
    最近更新 更多