在AngularJS中,如何在浏览器中点击重新加载按钮将数据存储到本地存储中?

时间:2017-05-02 07:21:20

标签: angularjs angular onclick local-storage

在AngularJS中,如何在点击浏览器中的重新加载按钮时将数据存储到本地存储中?

我尝试使用以下code.still,它无效

window.onbeforeunload = function (event) 
{
    var $body = angular.element(document.body);   

    var $localStorage = $body.injector().get('$localStorage');
    var logoutService = $body.injector().get('logoutService');

    if (typeof event == 'undefined') 
    {
        event = window.event;
    }

        else if (event.type == 'beforeunload') 
        {
            if(startAppCtrl.persDet !=undefined)
            {
                $localstorage.setItem('persDet',startAppCtrl.persDet);
            }else
            {
                startAppCtrl.persDet=$localStorage.getItem('persDet');   
            }        


        }
}

5 个答案:

答案 0 :(得分:2)

您可以向onbeforeunload事件添加事件监听器:

$window.onbeforeunload = function(e) {
  $window.localStorage.setItem('varName', varValue);
};

其中$window是对作为控制器函数中的参数传递的window对象的引用。

.controller('Ctrl', function(
    $scope,
    $window
){

  $window.onbeforeunload = function(e) {
    $window.localStorage.setItem('varName', varValue);
  };

  // don't forget to remove the listener when the controller is out of scope
  $scope.$on('$destroy', function() {
      delete $window.onbeforeunload;
  });

});

如果您不想在窗口上访问vanilla localStorage api,也可以使用ngStorage

https://github.com/gsklee/ngStorage

angular.module('app', [
            'ngStorage'
        ]).controller('Ctrl', function(
            $scope,
            $localStorage,
            $window
        ){
          ....
          $window.onbeforeunload = function(e) {
            $localStorage.setItem('varName', varValue);
          };
          ....
        });

答案 1 :(得分:2)

示例:与$ localStorage

相关
<html>
    <head>
        <title>LocalStorage Example</title>
    </head>
    <body>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
        <!-- Localstorage Dependency ngStorage -->
        <script type="text/javascript" src="https://cdn.jsdelivr.net/ngstorage/0.3.6/ngStorage.min.js"></script>
        <script type="text/javascript">
            //User this module  in your Angular APP
            var app = angular.module('MyApp', ["ngStorage"])
            //$localStorage is a services 
            app.controller('MyController', function ($scope, $localStorage, $sessionStorage, $window) {
                $scope.Save = function () {
                    $localStorage.LocalMsg = "You are using localStorage (JEET)";
                    $sessionStorage.SessionMsg = "You are using session storage (JEET)";
                }
                $scope.Get = function () {
                    console.log($localStorage.LocalMsg + "\n" + $sessionStorage.SessionMsg);
                }
            });
        </script>
        <div ng-app="MyApp" ng-controller="MyController">
            <input type="button" value="Reload" ng-click="Save()" />
            <input type="button" value="Get" ng-click="Get()" />
        </div>
    </body>
    </html>

答案 2 :(得分:1)

使用AngularJS通过服务处理本地存储。

本地存储服务:

公共工厂服务,它将根据密钥保存并返回保存的本地存储数据。

app.factory('storageService', ['$rootScope', function($rootScope) {

    return {
        get: function(key) {
            return localStorage.getItem(key);
        },
        save: function(key, data) {
            localStorage.setItem(key, data);
        }
    };
}]);

在控制器中:

在控制器中注入storageService依赖项,以设置并从本地存储中获取数据。

app.controller('myCtrl',['storageService',function(storageService) {

  // Save session data to storageService
  storageService.save('key', 'value');

  // Get saved session data from storageService
  var localStorageData = storageService.get('key');

});

答案 3 :(得分:0)

LocalStorage API使前端Web开发人员可以访问可用于在用户计算机上保存数据的简单键值数据存储。

您可以使用各种方法设置值并将其检索回来。

示例: 要将值存储在本地存储中,您可以使用以下命令:

// Functions
localStorage.setItem('name', 'Matt West');

// Object
localStorage.name = 'Matt West';

// Array
localStorage['name'] = 'Matt West';

要检索您可以使用的值

var name = localStorage.getItem('name');

答案 4 :(得分:0)

创建一个包含save和fetch方法的对象

//localStorage persistence
var STORAGE_KEY = "items";
//localStorage.clear();
var itemStorage = {
  fetch: function() {
    var saved = localStorage.getItem(STORAGE_KEY);
    var items = saved !== null
      ? JSON.parse(saved)
      : [
          {
            username: "Jondi Rose",
            fullname: "Alfred Jond Rose",
            point: 1234,
            notes: "super user"
          },
          {
            username: "Dulal",
            fullname: "Jonathan Smith",
            point: 23,
            notes: "new user"
          }
        ];
    items.forEach(function(item, index) {
      item.id = index;
    });
    itemStorage.uid = items.length;
    return items;
  },
  save: function(items) {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(items));
  }
};
$destroy上的

调用此方法。 如果使用SPA,您可以使用$routeChangeStart

$scope.$on('$routeChangeStart', function() {
    //callback
});