What is the method to save data into the browser's local storage when the reload button is clicked in AngularJS?

Is there a way to store data into the localstorage in AngularJS when the reload button is clicked?

I've tried using the code below, but it doesn't seem to work:

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


        }
}

Answer №1

One way to handle the onbeforeunload event is by adding an event listener:

window.addEventListener('beforeunload', function(e) {
  localStorage.setItem('uniqueVarName', uniqueVarValue);
});

In the example above, we're using the localStorage property of the window object to store a value.

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

  $window.addEventListener('beforeunload', function(e) {
    localStorage.setItem('uniqueVarName', uniqueVarValue);
  });

  // Remember to remove the event listener when the controller is no longer in use
  $scope.$on('$destroy', function() {
      $window.removeEventListener('beforeunload');
  });

});

If you prefer to avoid direct access to the vanilla localStorage API on the window object, you can utilize the ngStorage module:

https://github.com/gsklee/ngStorage

angular.module('app', [
            'ngStorage'
        ]).controller('Ctrl', function(
            $scope,
            $localStorage,
            $window
        ){
          ....
          $window.addEventListener('beforeunload', function(e) {
            $localStorage.setItem('uniqueVarName', uniqueVarValue);
          });
          ....
        });

Answer №2

Unique Example: Utilizing $localStorage

<html>
    <head>
        <title>$localStorage Usage Example</title>
    </head>
    <body>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
        <!-- NgStorage as a Localstorage Dependency -->
        <script type="text/javascript" src="https://cdn.jsdelivr.net/ngstorage/0.3.6/ngStorage.min.js"></script>
        <script type="text/javascript">
            //Incorporate this module into your Angular APP
            var app = angular.module('MyApp', ["ngStorage"])
            //$localStorage acts as a service 
            app.controller('MyController', function ($scope, $localStorage, $sessionStorage, $window) {
                $scope.Save = function () {
                    $localStorage.LocalMsg = "You are currently using localStorage (JEET)";
                    $sessionStorage.SessionMsg = "You are currently 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="Retrieve" ng-click="Get()" />
        </div>
    </body>
    </html>

Answer №3

Managing local storage with AngularJS service.

Local storage management service :

A common factory service designed to store and retrieve saved data in the browser's local storage using AngularJS framework.

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

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

In the controller :

Inject the storageService dependency to access and manipulate data in the local storage.

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

  // Save session data using storageService
  storageService.saveData('key', 'value');

  // Retrieve saved session data using storageService
  var localStorageData = storageService.getData('key');

});

Answer №4

The LocalStorage API provides front-end web developers with a convenient way to store and retrieve data on a user's device.

There are multiple methods available for setting and retrieving values from the local storage.

Here is an example of how to store values in the local storage:

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

// Using object property
localStorage.name = 'Matt West';

// Using array notation
localStorage['name'] = 'Matt West';

To retrieve the stored values, you can use the following code:

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

Answer №5

Create a custom object that handles saving and retrieving tasks.

//Task persistence using localStorage
var STORAGE_KEY = "tasks";
//localStorage.clear();
var taskStorage = {
  fetch: function() {
    var savedTasks = localStorage.getItem(STORAGE_KEY);
    var tasks = savedTasks !== null 
      ? JSON.parse(savedTasks)
      : [
          {
            name: "Complete project",
            priority: "High"
          },
          {
            name: "Send email",
            priority: "Medium"
          }
        ];
    tasks.forEach(function(task, index) {
      task.id = index;
    });
    taskStorage.uid = tasks.length;
    return tasks;
  },
  save: function(tasks) {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks));
  }
};

Call this method when the component is being destroyed. You can also use $routeChangeStart event for single page applications (SPA).

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason for not being able to retrieve params in resolve functions?

When creating a show page, I encountered an issue with ensuring the data is available before displaying the page. Traditionally, I would use the resolve property in a route to achieve this, but with ui-router, I do not have access to attributes in $state ...

Adjusting the content of mat-cards to fill in blank spaces

I have encountered an issue with the alignment in a list using mat-card. Here is my current layout: https://i.stack.imgur.com/VKSw4.jpg Here is the desired layout: https://i.stack.imgur.com/8jsiX.jpg The problem arises when the size of content inside a ...

There are no versions available for Angular NPM that match [email protected]

Here is the contents of my .npmrc file: registry=https://pkgs.dev.azure.com/<yourOrganization>/_packaging/<yourFeed>/npm/registry/ always-auth=true After deleting node_modules and attempting to install the packages, I encountered the follo ...

Filter through the array of objects using the title key

I'm attempting to extract specific data by filtering the 'page_title' key. Below is a snippet of my JSON object: { "page_components": [ { "page_title": "My Account", "row_block": [ { "heading": "", "sub_headi ...

html The "download" attribute causing a new tab to open rather than initiating a

I have a website built with Angular 4, where users can download images from an Amazon S3 bucket. However, I encountered an issue wherein instead of downloading the image, it opens in a new tab. I've tested this problem on different browsers such as Fi ...

Angular: Navigating to a distinct page based on an API response

In order to determine which page to go to, based on the response from an API endpoint, I need to implement a logic. The current API response includes an integer (id) and a string (name). Example Response: int: id name: string After making the API call, I ...

Update object properties in Angular controller dynamically

Take a look at my simple plunker Within the code, I am attempting to link a scope variable to an object property. $scope.name = 'World'; var obj = { "name":$scope.name } $scope.$watch('name', function(){ console.log(obj["name"]); ...

After successfully uploading a file, refresh the file list using AngularJS, DropzoneJS, and JSON

In my "file manager page," I am using DropzoneJS for uploading files and AngularJS ng-repeat to display all the saved files. The file list is retrieved through an ng-controller that uses an http.get request to fetch a JSON file with the file list. When Dr ...

Having trouble with Angular 5's Post function?

Having some trouble with my Angular 5 application and API calls. For some reason, when I add headers to the request, the browser is not recognizing them properly and showing 'OPTION' instead of the actual headers. This is resulting in a 403 respo ...

The width of Kendo Angular 2 grids pager and top header does not increase when scrolling

Our grids now have the horizontal scrolling feature enabled through CSS (kendo-grid {overflow: auto;}). However, we've noticed that the pager and top header of the grids do not expand their width when scrolling. Take a look at the screenshot below: ...

The error message TS2339 in Angular service.component indicates that the property 'subscribe' is not recognized on the type 'Promise<Object>'

Currently, I am in the process of learning Angular by developing a web application for my parish. I have implemented a method for deleting items in the products-list.component.ts file which appears to be technically correct. However, when I attempt to run ...

Retrieving information from MongoDB

Currently, I am working on retrieving data from MongoDB and passing it to my Express server to eventually display it in my HTML using Angular. The retrieval process is successful when there is only one record in the database. However, if multiple records a ...

`Angular Image Upload: A Comprehensive Guide`

I'm currently facing a challenge while attempting to upload an image using Angular to a Google storage bucket. Interestingly, everything works perfectly with Postman, but I've hit a roadblock with Angular Typescript. Does anyone have any suggesti ...

Angular JavaScript Object Notation structure

I am a beginner in AngularJS and I'm attempting to create formatted JSON based on the values of table rows (tr) and cells (td). The table rows are generated automatically. When the form is submitted, I try to create the JSON values. Once the form is ...

There is no index signature that accepts a parameter of type 'string' in the type '{ [key: string]: AbstractControl; }'

I'm currently tackling a challenge in my Angular project where I am creating a custom validator for a reactive form. However, I've encountered an error within the custom validators function that I am constructing. Below you will find the relevan ...

Using Angular to make a DELETE request using HttpClient with a Json Server

My goal is to remove one employee at a time from the Employees list. The Observable is configured in employee.service.ts and subscribed in app.component.ts. However, there seems to be an issue connecting the id of the employee with the removeUser(id) metho ...

The Angular Progressive Web App functions properly in ng serve mode, but encounters issues when running with http-server

I'm developing a Progressive Web App (PWA) using Angular. Everything was functioning smoothly until out of nowhere, I started encountering a 404 Error whenever I tried to navigate to a new component while serving in dist/project with http-server. Surp ...

When I try to pass a formControl to a child component in Angular, it throws a "no value

What could be causing the error message "no value accessor for form control with unspecified name" to appear? I am working with the edit-component: Here is the code in HTML: <mat-form-field> <input [formControl]="formControl"> </mat-f ...

How can you conceal an element once the ngHide animation has completed in Angular's ngAnimate?

Is there a way for the display to be set to "none" after the ng-hide animation has completed, instead of immediately when the element is hidden? ...

Issue with clearing subscription upon navigating to another page is not functioning as expected

Currently, I am working on building a basic search screen to gain a better understanding of Angular subscriptions, which I have found to be quite perplexing. On my home page, I have set up two components - one for filtering and the other for displaying sea ...