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

时间:2022-06-24 17:29:11

In AngularJS how can i store data into the localstorage on click of reload button in the browser?

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

I tried with the following code.still, it's not working

我尝试使用以下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 个解决方案

#1


2  

You could add an event listener to the onbeforeunload event:

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

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

Where $window is a reference to the window object passed as a parameter in your controller function.

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

});

You could also use ngStorage if you don't want to access the vanilla localStorage api on window.

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

https://github.com/gsklee/ngStorage

https://github.com/gsklee/ngStorage

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

#2


2  

Example : related from $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>

#3


1  

Handling local storage through service using AngularJS.

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

Local storage service :

本地存储服务:

Common factory service that will save and return the saved local storage data based on the key.

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

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

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

In controller :

在控制器中:

Inject the storageService dependency in the controller to set and get the data from the local storage.

在控制器中注入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');

});

#4


0  

The LocalStorage API gives front-end web developers access to a simple key-value datastore that can be used to save data on a users computer.

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

You have various methods to set the value and to retrieve them back .

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

Example : For storing the values in local storage you can use the following :

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

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

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

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

For retrieving the values you can use

用于检索您可以使用的值

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

#5


0  

Create an object containing save and fetch methods

创建一个包含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));
  }
};

on $destroy call this method. You can use $routeChangeStart if working on SPA.

on $ destroy调用此方法。如果在SPA上工作,您可以使用$ routeChangeStart。

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

#1


2  

You could add an event listener to the onbeforeunload event:

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

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

Where $window is a reference to the window object passed as a parameter in your controller function.

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

});

You could also use ngStorage if you don't want to access the vanilla localStorage api on window.

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

https://github.com/gsklee/ngStorage

https://github.com/gsklee/ngStorage

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

#2


2  

Example : related from $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>

#3


1  

Handling local storage through service using AngularJS.

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

Local storage service :

本地存储服务:

Common factory service that will save and return the saved local storage data based on the key.

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

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

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

In controller :

在控制器中:

Inject the storageService dependency in the controller to set and get the data from the local storage.

在控制器中注入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');

});

#4


0  

The LocalStorage API gives front-end web developers access to a simple key-value datastore that can be used to save data on a users computer.

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

You have various methods to set the value and to retrieve them back .

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

Example : For storing the values in local storage you can use the following :

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

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

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

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

For retrieving the values you can use

用于检索您可以使用的值

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

#5


0  

Create an object containing save and fetch methods

创建一个包含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));
  }
};

on $destroy call this method. You can use $routeChangeStart if working on SPA.

on $ destroy调用此方法。如果在SPA上工作,您可以使用$ routeChangeStart。

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