Attempting to switch routes results in an undefined value for rootScope

Upon user login, the following code is executed:

var promise = UserFactory.doLogin(userCredentials);

promise.success(function (data, status) { 

  //set localstorage variables
  //retrieve additional data only upon successful login

   var anotherPromise = UserDataFactory.getUserData();                                   
    anotherPromise.success(function (data, status){                                      
           if(data.code == 2){                                                     
               $rootScope.userHead = true;
             }

});

The value of $rootScope.userHead dictates whether a sub-menu is shown or hidden. The related HTML snippet for the sub-menu looks like this:

<div class="panel panel-default text-center" style="text-align: center;" ng-hide="userHeader">

The menu page is included in various pages using

<div id="submenu" ng-include="'submenu.html'" ></div>
, and these pages are accessed through routes such as:

            .when('/user', {                    
               templateUrl: 'user.html',                         
               controller: 'userController',
               animation: 'second',
               access: {
                    requiredLogin: true
                }
            }) 
           //user.html includes menu with ng-include="'submenu.html'"

After loading the user page, $rootScope.userHead retains its value and the sub-menu remains hidden. However, upon refreshing the page, $rootScope.userHead becomes undefined and the submenu becomes visible.

Is there a reason why $rootScope.userHead loses its value when navigating to another page? Shouldn't it maintain its value?

I'm struggling to identify the issue here. Any insights on how to resolve this would be greatly appreciated.

Thank you.

Answer №1

When you refresh your page, any data stored in JavaScript variables will be erased. The $rootScope is simply a variable in JavaScript. If you need to retain information even after a page refresh, there are several options available:

  • Utilize a Cookie (such as the $cookieStore in Angular)
  • Take advantage of HTML5 features like Local Storage, Web DB, or the traditional DOM Storage (http://en.wikipedia.org/wiki/Web_storage)
  • Save your data on a server
  • Consider using ngStorage

Written by: Micheal.

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

Using AngularJS for posting data without specifying a default value input may lead to unexpected results

I'm curious about why the input is not working when a default value is assigned to the controller and then posted as undefined on the server side. However, if you type directly into the input, it works fine and the value is captured. What's the d ...

Change the background color according to the user's input text

I want to create a text box where users can input color keywords like blue, lime, or black. When they click submit, I want the background color of the page to change accordingly. This is what I have so far: <label for="color">Color: </label> ...

What are the steps to effectively utilize my search bar alongside Google Custom Search?

Here is the HTML code for my form: <form action="#" class="searh-holder"> <input name="se" id="se" type="text" class="search" placeholder="Search.." value="" /> <button class="search-submit" id="submit_btn"><i class="fa fa-sea ...

Can we actually modify the state using useReducer?

I'm currently diving into the world of useReducer function while exploring ways to create a react-based quiz selection screen. My main objective is to update the state so that it can be accessed by the main App component for broader usage. However, I ...

Making an AJAX request to a different domain

My understanding is that the AJAX cross-domain policy prevents me from simply making a call to "http://www.google.com" using an AJAX HTTP request and then displaying the results on my website. I attempted to use the dataType "jsonp", which theoretically s ...

The list filter may not work properly if the search string is left blank

I am currently working on a list filtering feature that updates based on user input. As the user types, the system compares the entered text against the items in the list and displays the matching objects in an array. However, I'm facing an issue - wh ...

What is the best method for sending environment variables to a web extension?

I am in the process of developing a web extension that integrates with various AWS services, and I am facing challenges in securely storing and accessing API keys. Despite my attempts to pass API keys using conventional methods, such as running the comma ...

"Image Reactor: Unleashing the Power

I'm struggling to understand why my relative path image loading isn't functioning correctly. The assets are located within the src folder in my working directory, but for some reason, they're not displaying as expected. When I directly impo ...

What could be the possible reason for the controls in my element getting disabled due to adding a JavaScript background

First and foremost, I want to share a link with you to a page that I am currently developing so you can better understand the situation: Additionally, here is a link to the background effect: https://github.com/jnicol/particleground If you visit the page ...

How can I configure the CSRF cookie name and header in Protractor to send a POST request to a Django server in order to set up a fixture for testing an Angular

I am facing a challenge with my Protractor test as I need to send a post request to a Django server to insert a fixture. In order to make this post request, I must adjust the xsrf setting within my app: app.config(['$httpProvider', function($htt ...

Rendering an array of objects in React

Struggling to display the products array on my page, nothing seems to be showing up. I've experimented with rendering simpler elements like li and it worked fine, but when it comes to more complex content, I'm hitting a roadblock constructor(pro ...

adjustBounds and expand - appearing in an entirely new location

var classBounds = new google.maps.LatLngBounds(); var query = ""; query = "SELECT 'ROAD_NUMBER', 'geometry' FROM [TABLE_REFERENCE_ID] WHERE 'ROAD_NUMBER' CONTAINS IGNORING CASE '" + searchString + "' AND 'LINK_ ...

Exploring AngularJS capabilities: iterating over a collection of objects generated by a method

My latest project involves retrieving data from an API using a controller. Here's the code snippet: .controller('MyDataController', ['$http', function($http) { pdc = this; pdc.projects = [] pdc.getData = function(val ...

Unable to import TypeScript modules unless the file extension is explicitly specified

As someone new to TypeScript, I was under the impression that I could import my TS files without specifying their file type. Currently, I have to write: import {sealed} from "./decorators/decorators.ts"; Instead of what I believe should be the correct w ...

Bind a collection of Firestore documents dynamically using Vuexfire

I currently have a collection of firebase documents stored in a vuex state that is dynamically updated. My goal is to bind these documents with vuexfire dynamically as they are added or removed from the list. state: { docsToBind: [], // This array is dy ...

Using Firebase to loop through elements is made possible with ng

I'm currently faced with the challenge of using an ng-repeat to iterate through some JSON data that I have imported into Firebase. Below is the snippet of HTML code that I am working with: <div class="col-md-4" ng-repeat="place in places"> &l ...

Using CoffeeScript to Invoke Methods

I'm still learning CoffeeScript and encountering some challenges with calling methods. Can someone help me out? Here is the Card model I am working with: class exports.Card extends Backbone.Model defaults: pip: '4' suit: &apos ...

npm is consolidating all dependencies and their sub-dependencies into a single unified directory

My project has a package.json file with approximately 20 dependencies. Upon running npm install, all the dependencies and sub-dependencies end up in the main node_modules directory, resulting in hundreds of modules rather than just my intended 20. The sub- ...

angularjs ng-click event not functioning properly

I am a beginner in angularjs and I am encountering an issue with the ng-click event. It seems that the problem lies within the click event itself, but I'm not sure how to fix it. An error occurs when clicking the button: Error: $event is not defin ...

AngularJS - dynamically displaying updated content based on dropdown selection

I have implemented two dropdown lists using the select tag. I want to dynamically update the options in the second dropdown based on the selection from the first dropdown, and then display relevant information underneath based on the selection from the sec ...