Is your angularjs localstorage giving you trouble?

I am encountering an issue with local storage on my webpage. Upon initial visit, I am seeing an outdated value from local storage. However, upon refreshing the page, I am able to access the current value. How can I prevent this error and ensure that I only retrieve the most up-to-date local storage value every time? The code snippet provided attempts to address this issue without utilizing ngstorage. Do I need to install ngstorage in order to resolve this problem?

.controller('SignInCtrl', [
         '$scope','$http' ,'$location','$window', 
        function($scope,$http, $location,$window) {

    $scope.signin = function() 
{ 
 
$http.post('***', userdetails).success(function(data,response) 
{
var nameResponse = JSON.stringify(data.Name);
window.localStorage.setItem("name",nameResponse);


})


            }

 }])
 
 .controller('MyprofileCtrl', [
         '$scope','$http' ,'$location','$window', 
        function($scope,$http, $location,$window) {

var name=$window.localStorage.getItem("name");
//console.log(name);
if(name == null)
{

$scope.loginstatus ="Sign Up With Us";
console.log($scope.loginstatus);
}else
{
$scope.loginstatus ='Welcome '+ name.replace(/\"/g, "");
console.log($scope.loginstatus);
}

    
 } ])
 

Answer №1

Absolutely, you are correct! It is essential to utilize the ngstorage module.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.3/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.7/ngStorage.min.js"></script>
</head>
<body ng-app="myModule">
<div ng-controller="myCtrl">
        <button ng-click="save()">Save</button>
        <button ng-click="load()">Load</button>
        <input type="text" ng-model="txt">
        {{myData}}
    </div>
</body>
<script>
    var myModule = angular.module("myModule", ["ngStorage"]);
    myModule.controller("myCtrl", function($scope, $localStorage) {
        $scope.txt = "prabhu";
        $scope.save = function() {
        alert($scope.txt)
            $localStorage.message = $scope.txt;
        }

        $scope.load = function() {
            $scope.myData = $localStorage.message;
        }
    });
</script>
</html>

Answer №2

Not at all, ngStorage is not a necessity here. As long as the dependency for $window is injected correctly in your controllers, you should be good to go.

You can follow this code snippet:

var app = angular.module('your-app', ['the-dependent-modules']);

app.controller('loginController', function($window) {
   $window.localStorage.setItem('user-name', 'Sarah');
});

app.controller('profileController', function($window, $log) {
   var username = $window.localStorage.getItem('user-name');
   $log.debug('Logged in user: ' + username);
});

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

Are you in need of a JavaScript data validation tool?

Trying to find a library that can validate input in a specific format, such as: { points: array of { x: positive and less than 20, y: positive and less than 15 } } Ideally, it should work on both server and client sides and either return a boolean or th ...

Implement jQuery to close multiple div elements

My dilemma involves a series of divs with different manufacturer IDs listed as follows: manufacturer[1], manufacturer[2], manufacturer[3], ... etc ... In attempting to create a JavaScript for loop to hide each div, I discovered that it was not achievab ...

Retrieve the key values from an object of a generic type

Is there a way to retrieve the keys of the object when it is of type T? I attempted to accomplish this using different methods such as: function getGenericTypeKeys<T>(): string[] { return Object.keys({} as T); } and function getGenericTypeKeys< ...

Guide for Sending a Textnode from One Page to a Different Page within a Specific Id Element through PHP

firstpage.html : <body> <?php $text = $_POST['text']; ?> <p style = "color:red; " id = "getext"><?php echo $text; ?></p> </body> secondpage.php : <body> <?php $text = $_POST['text']; ?> ...

Is it possible to deploy Vue.js from a content delivery network (CDN) for production

My decision to use Vue.js for a new project was influenced by its ability to run natively in the browser, unlike React which requires compilation/transpilation via Node. I'm considering linking directly to a CDN like this in my production code: <s ...

div.load() results in a complete page reload

When I save form data, my goal is to load only the specific div without refreshing the entire page. However, despite using the preventDefault() command, the form still seems to be posting the whole page. I have tried adding the following code: $("#btn ...

Nestjs struggles with resolving dependencies

Having trouble finding the issue in my code. (I'm still new to nestjs and trying to learn by working on some apps). The console log is showing the following error: Nest can't resolve dependencies of the UrlsAfipService (?). Please ensure tha ...

Avoid accidental overwrites in localStorage using JavaScript

I've been working on a Vue project where I'm implementing a shopping cart feature. In this setup, when the user clicks on a button, the item details are stored in localStorage and then displayed in the shopping cart interface. However, I encount ...

Encountering module resolution issue following npm-link for the shared component repository

Attempting npm-link for the first time to establish a shared component repository, and encountering an issue. The project seems to be linked correctly based on this message: /Users/tom.allen/Development/main/project/node_modules/@linked/project -> /usr ...

AngularJS Karma unit tests experiencing issues with loading Jasmine matcher functions

Currently, I am in the process of developing unit tests for an AngularJS application. For testing purposes, I have opted to use the Karma test runner along with the Jasmine framework. The specific function that is being tested aims to retrieve objects fro ...

Having difficulty replicating the same effect across all five canvas elements

After following the code provided by j08691 here for canvas, everything worked flawlessly. However, I encountered an error in JavaScript when trying to implement it on multiple canvas elements. As a beginner in JavaScript, I would greatly appreciate any as ...

Using React.js - What is the process for submitting a form automatically when the page loads?

Upon loading the page, I have a form that needs to be displayed. Here is the code snippet: <form name="myform" method="POST" className={classes.root} target="mydiv" action="https://example.com/submit" onLoad= ...

Clicking on the button will allow you to sort the items in

I need assistance with sorting a table: when I click on a header, the order changes to ascending but does not toggle back to descending. Despite having a boolean value that should switch between true and false, it keeps returning the initial value. Can s ...

retrieve the previous value from the scope

Attempting to create a copy of an event before any changes are made in order to implement a cancel button, I stored it in the oldValue variable. However, both the event and oldValue variables appear to be empty because they are executed before the event fa ...

Troubleshooting Timeout Problems with Selebiun Crawler in C#

I am encountering an error while running the following code. public void GetCategoriesSelenium() { string javascript = System.IO.File.ReadAllText(@"GetCategory.js"); CrawlerWebSeleniumJS.ExecuteScript("var finished;"); ...

When the margin-left changes, SVG begins to flicker and shake in a marquee effect

I've been experimenting with a marquee effect using vanilla JS. The effect is working, but I'm encountering some shaking issues with SVG and images as they move. <div class="marquee"> <h1>Nepal <svg version="1.1&qu ...

Experiencing difficulty in connecting with the service providers

What's the process for obtaining these providers? I recently followed the JavaScript Mastery tutorial step by step, however, I encountered an issue with the useEffect hook to fetch the providers (I even tried using alert to check, but it keeps showin ...

Discover the Mongoose Document and Arrange in a Random Order with Various Levels?

I am currently using a .find() method to sort documents in a collection based on their "status" and ordering them by most recent. Is it possible to first sort by status, and then randomly sort within each tier? For example, I have users divided into three ...

Is it necessary to establish a connection to my mongodb database directly within my jest test file, or is it permissible to invoke functions from separate classes that handle the database connection?

Currently in the process of testing my database functions using jest. My javascript file contains a variety of functions that connect to the database, retrieve data, and return an array. The issue I'm facing is when calling these functions from my jes ...

Setting the initial state for your ngrx store application is a crucial step in ensuring the

I'm completely new to ngrx and I'm currently exploring how to handle state management with it. In my application, each staff member (agent) is associated with a group of customers. I'm struggling to define the initial state for each agent ob ...