【问题标题】:Bind view to localStorage value将视图绑定到 localStorage 值
【发布时间】:2018-11-03 07:56:20
【问题描述】:

我正在构建一个移动应用程序(使用 ionic),它将发出一个 http 请求来更新视图。但是我想在 ajax 调用获取新数据时显示旧值。 我的想法是使用localStorage。我将显示来自 localStorage 的旧数据,一旦 ajax 调用带回我想要更新 localStorage 的新数据。所以我尝试使用 ngStorage。但它根本不起作用。 这是代码的样子: 控制器

angular.module('starter.controllers', ['ngStorage'])
.controller('Ctrl', function($scope, $localStorage){
  $scope.$storage = $localStorage;
})

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.10/ngStorage.js"></script>
  </head>
  <body ng-app="starter">

    <div ng-controller="Ctrl">
      {{$storage.x}}
    </div>

本地存储是这样的:

Storage {x: "This should be attached to HTML"}

知道我做错了什么吗?

【问题讨论】:

    标签: angularjs mobile ionic local-storage


    【解决方案1】:

    试试这个数据绑定

    angular.element($window).on('storage', function(event) {
        if (event.key === 'my-storage') {
          $rootScope.$apply();
        }
      });
    

    你可以把它包装在工厂里

    app.factory("LS", function($window, $rootScope) {
      angular.element($window).on('storage', function(event) {
        if (event.key === 'my-storage') {
          $rootScope.$apply();
        }
      });
      return {
        setData: function(val) {
          $window.localStorage && $window.localStorage.setItem('my-storage', val);
          return this;
        },
        getData: function() {
          return $window.localStorage && $window.localStorage.getItem('my-storage');
        }
      };
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-21
      • 2021-07-02
      • 1970-01-01
      • 2013-04-05
      • 1970-01-01
      相关资源
      最近更新 更多