Why does refreshing a page in AngularJS cause $rootScope values to disappear?

On my local route http://localhost:9000/#/deviceDetail/, there is a controller that handles the view. Before navigating to this view, I set certain variables on the $rootScope (such as $rootScope.dashboards).

While on the view, I have access to the dashboards property. However, upon refreshing the page using the F5 key, the dashboards property gets lost.

I attempted to save the $rootScope in the localStorage variable, but encountered circular reference issues with the JSON.stringify method.

Does anyone have any suggestions on how to address this issue?

Answer №1

When using AngularJS, all data is stored in the memory heap which begins when a page is opened and ends when the page is closed. Refreshing the browser is equivalent to closing and reopening the page.

To preserve values after a refresh, it is recommended to store them in a cookie. This can be done using $cookies, sessionStorage or localStorage as suggested by M K.

Answer №2

After attempting to save the auth token using cookies based on a tutorial found at Getting started with AngularJS and ASP.NET MVC - The long awaited Part Three, I encountered an issue where the cookies were being destroyed every time I refreshed the Chrome browser or hit F5.

The article suggested that ngCookies could help maintain tokens through page refreshes, but unfortunately, it did not work as expected. After hours of researching online, I came across advice from M K recommending the use of localStorage (or sessionStorage) instead of cookies. The lesson learned was that relying on cookies for storing authentication tokens is not a good practice and can lead to unexpected bugs, as highlighted in the aforementioned article.

I am grateful to M K for pointing me in the right direction and helping me resolve this issue.

Answer №3

To implement localStorage and check for $stateChangeStart when using ui.route, you can use the following code snippet:

$rootScope.$on('$stateChangeStart', function(event, toState) {

            // Retrieve user data from localStorage and convert it to an object
            var userData = JSON.parse(localStorage.getItem('user'));            

            if(userData) {

                $rootScope.currentUser = userData;

            }
        });

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

The evaluation of jQuery did not function properly on the less.css file

I have a jQuery function that I am using as shown below @winheight:`$(window).height()` within my less file. However, when I compile it to CSS, I encounter a compiler error I am currently using a software called Crunch Compiler Errors You are usin ...

Enhance Your Search Experience with Angular

I recently developed an Angular app that searches through a database of objects. However, a problem arises with the search filters as they match any part of the string, resulting in irrelevant search results. For example, when searching for the name "Stev ...

What is the best way to display a particular JavaScript variable in an HTML document?

Is there a way to display the value of a Javascript variable in an HTML form, such as showing it on the screen? Below is my JavaScript code: <script type="text/javascript"> var howLongIsThis = myPlayer.duration(); </script> The variable howL ...

I am experiencing issues with local storage getItem() function not functioning properly within NUXT JS

Currently working on creating a shopping cart using nuxt js. Successfully able to store the cart data in local storage, but facing difficulty in retrieving the data. Refer to the screenshots for more details: https://i.sstatic.net/X7dL9.png https://i.sstat ...

The functionality of passing an ID in Bootstrap Modal is not functioning as expected

I'm facing an issue with passing an ID to my modal. My goal is to have the details of an event displayed in the modal when the corresponding link (which represents the event) is clicked. However, I'm struggling to retrieve the ID and show the ev ...

What is the best way to retrieve a value from a button function in order to utilize it in AJAX requests and SQL queries?

Having an edit button that allows users to change category names. When the edit button is clicked, a pop-up alert appears with an input field. Users can type in the input field, press okay, and the value should update with the input. This is the current co ...

What is the correct way to format responses written within response.write() in NodeJS?

Just starting out with NodeJS and express and following a tutorial on displaying two headings in the browser. Came across an issue where using res.send() twice wasn't working, so my instructor introduced me to the write method. Interestingly, when she ...

creating a function that sends two separate fetch requests with a pause in between each request

Currently, I am working with 2 endpoints. The first one requires a "post" request, and upon receiving the response, it should provide me with an ID that is used in the URL of the second endpoint. To ensure that I can obtain this ID before proceeding with ...

Utilize Node Package to Dispatch Firebase Push Notifications

I am currently experimenting with a NodeJS module for sending Push Notifications. I have been exploring the 'node-sender' module but have not been able to find an option for sending notifications to a web browser for testing purposes: https://w ...

The server receives `/client/:id` in place of the real id

Front-end Development customer.controller("single_customer", function($scope, $http, $routeParams) { $http.get('http://localhost:4000/customer/:id').then (function(data){ // $scope.whichCustomer = $r ...

Modify a JavaScript variable dynamically using an external source

I currently have two files named data1.js and data2.js. In data1.js, there is a variable defined as: var rows = ['g1', 'g2']; Whereas in data2.js, the variable is defined differently as: var rows = ['g1', 'g2', &a ...

transferring scoped model information to the controller

When using AngularJS, my view is structured like this: <div class="sli1" ng-init="values=[10,20,30,40,50]" <div class="sli2" ng-init="values2=[10,20,30,40,50]" I am attempting to send the initial data models back to the controller for retrieva ...

Generating a dropdown menu in HTML using JSON entities

I am attempting to populate an HTML Select element with data retrieved from JSON. Below is a simplified version of the JSON object: {"Group1": "TestGroup1", "Group2" : "TestGroup2", "TotGroups" : "2"} To achieve this, I am using JQuery and AJAX for fetch ...

Express: router.route continues processing without sending the request

I've implemented the following code in my Express application: var express = require('express'); // Initializing Express var app = express(); // Creating our app using Express var bodyParser = require(' ...

The styles applied to the Angular 5 Component host element are not being reflected correctly in jsPlumb

As a beginner in Angular >2 development, I am excited to build my first application from scratch. One of the features I'm trying to implement is drawing flow charts using jsPlumb. However, I have encountered an issue where the connectors are not be ...

Experiencing Strange Issues with Jquery Image Carousel... Assistance Needed!

I recently created a jquery slideshow using a tutorial I found at this link: While the slideshow is functioning correctly for the most part, there is a strange issue that occurs right at the beginning when displaying the first image. Initially, the first ...

In Javascript, what significance does the symbol ":" hold?

While exploring the Ionic framework, I came across the following code snippet: import { AlertController } from 'ionic-angular'; export class MyPage { constructor(public alertCtrl: AlertController) { } I'm curious about the significanc ...

Is there a way to use HTML and JS to draw custom lines connecting elements?

Sorry if this question has been asked before. Is there a way to create straight lines connecting HTML elements with just HTML and JavaScript, without relying on SVG or Canvas? If so, what would be the most effective approach? ...

Using jQuery to toggle the visibility of a group of radio buttons causes the div to quickly appear and disappear

My code is working perfectly as it shows up when needed and disappears when necessary. The concept behind this form is that the user can check a box, view more required form data related to the checked item, make those fields required, and then uncheck the ...

Configure Protractor's configuration file to utilize a personalized reporter

I'm in the process of setting up end-to-end tests using protractor.js, but I am not happy with how the default reporter displays results on my terminal window. Is there a way to customize the reporter configuration to make it easier to read and more ...