Tips for efficiently managing user details across multiple controllers in AngularJS

Hello everyone, I'm wondering how I can manage user session ID and name across view controllers in AngularJS.

Here's the scenario: I made an HTTP call and retrieved the user ID and name. Now, I want to be able to access this information in any controller.

I attempted to use an Angular value service by setting:

app.value("user",{user_id:"0",user_name:"blank"})

And in a controller where the HTTP call is made:

app.controller("exampleCtrl",function($http,user){
      user.user_id = data.user_id;
      // Let's say the user ID is 4.
      // Now user.user_id should also be 4
})

But, in another controller:

app.controller("nextCtrl",function(user){
    console.log(user.user_id);
    // This gives me 0 instead of 4
})

I expected it to return 4. Am I approaching this the wrong way? Is there a better way to achieve this? Please provide guidance.

Thank you!

Answer №1

There are several options available for sharing data in AngularJS, such as:
$sessionStorage, localStorage, appConstant, $localStorage, and more.

You can also share data between controllers using Factory and Services.

If you simply want the variable to be accessible throughout the controller, here is a simple example using $sessionStorage.

To utilize $sessionStorage or $localStorage, make sure to include ngStorage:

Start by adding the following source to your index.html:

 <script src="https://rawgithub.com/gsklee/ngStorage/master/ngStorage.js"></script>  

Next, inject ngStorage into your module definition:

var app = angular.module('Your App Name', ['ngStorage']);

Your HTTP CALL:

app.controller("exampleCtrl",function($http,user,$sessionStorage){
      user.user_id = data.user_id;
      $sessionStorage.user_id = data.user_id;
      //assuming the user id is 4.
      //now user.user_id should also be 4
})  

To access it in another controller, you can do this:

app.controller("nextCtrl",function(user,$sessionStorage){
   console.log($sessionStorage.user_id);
    //outputs 4 which can then be assigned to any variable you prefer
    console.log(user.user_id);
    //outputs 0 instead of 4 ?
})  

The following PLUNKER demonstrates using factory and $sessionStorage to share data between controllers:
http://plnkr.co/edit/XPHwKQYcSCk3GSilvFtE?p=preview

Answer №2

Angular includes a handy module called ngCookies that makes managing cookies a breeze!

var app = angular.module("myApp", ["ngCookies"]);

ngApp.factory("userCookieService", [
"$cookies", function($cookies) {
    var currentUserName = "";

    return {
        setUserDataInCookie: function(username) {
            currentUserName = username;
            $cookies.put("userName", username);
        },
        getUserDataFromCookie: function() {
            currentUserName = $cookies.get("userName");
            return currentUserName;
        },
        clearCookieData: function() {
            currentUserName = "";
            $cookies.remove("userName");
        }
    }
}
]);

Answer №3

If you're looking for a quick fix, consider saving it in the $rootScope: AngularJS utilizing $rootScope as a data storage. (Chances are you won't need to update it frequently).

If you're open to adding a dependency, check out this Angular extension: https://github.com/gsklee/ngStorage. It offers great control over the lifespan of your stored data: HTML5 Local storage vs. Session storage

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 best way to retrieve the updated window dimensions following a rotation of an iPad screen?

I need to update the size of a specific element on a webpage based on screen rotation, especially for iPads and all other mobile devices. The new dimensions should be calculated according to the updated screen size. While attempting to implement this, I e ...

Utilizing an array of objects with AngularJS and posting them using JSON in a Spring method

I'm looking to interact with a web-service that posts an array of objects using AngularJS. The web-service is functioning correctly, but I encountered an error when trying to consume it with AngularJS: "Can not deserialize instance of java.util.ArrayL ...

Argument typed with rest properties in Typescript objects

I'm relatively new to Typescript and have managed to add typings to about 90% of my codebase. However, I'm struggling with rest/spread operators. While going through our code today (which I didn't write), I came across this snippet that does ...

Validation of Numbers and Characters in DevExpress ASP.NET TextBox

When I try to use masking on the textbox for credit card format, I am having trouble entering a hyphen. It seems that the validation does not accept dashes as I only checked for numbers. Any help would be appreciated. Thank you. <script> functio ...

Navbar not displaying output in React JS

I followed a tutorial on YouTube to create a navbar using Bootstrap and React, but I'm facing issues with the output. The YouTube tutorial used HTML along with Bootstrap to make the navbar. Even though the classes are similar, all I can see is a small ...

Modifying the background image of div elements with JQuery in a loop function is ineffective when using Google Chrome

I am facing an issue in my application where I have a for loop to change the background image of two divs. The code snippet is as follows: for (var i = 0; i < length; i++) { $("div_" + (i + 1)).css("background-image", "../imageFile.png"); ...

Steps for canceling a promise using $resource in AngularJS version 1.5

I am currently using angular 1.5.7 and I am facing an issue where a delete operation on a resource is taking too long to complete. I am working with a MEAN stack and there are times when the delete operation appears to be pending, making me wonder if Mongo ...

Adding a Timepicker to a Datepicker on a jsp webpage with javascript

I am working on a JSP page that includes a date picker. I want to enhance this datepicker by adding a start time and end time within the calendar itself. How can I achieve this? Additionally, I need to implement validation ensuring that the start time is a ...

The AngularJS error message states that there is an issue because the $resource function is

I am currently facing an issue with my controller, specifically the error message: TypeError: $resource is not a function This error is pointing to the line var Activities = $resource('/api/activities'); app.controller('AddActivityCtrl& ...

Tips for postponing the execution of inline javascript

Main page <script> $.ajax({ type: 'GET', url: 'ajax.php', context: document.body, success: function(data) { $("#content").html(data); } }); </script> <div id="content"></div> Ajax ...

Tips for extracting key values from an array of objects in Typescript

I am working with an array called studyTypes: const studyTypes = [ { value: "ENG", label: "ENG-RU", }, { value: "RU", label: "RU-ENG", }, ]; Additionally, I have a state variable set ...

React.js: The function useDef has not been defined

Attempting to create a React.js calculator application, my initial step was to delete the entire src folder and replace it with a new one containing the necessary elements for the web app. Here is the content of the index.js file: import React,{ useEffect, ...

What is the solution for the error "BREAKING CHANGE: webpack < 5 used to automatically include polyfills for node.js core modules"?

I am trying to use the "web3" and "walletconnect/web3-provider" package in a Vue & Laravel 8 project. I have installed it using the npm i --save web3 @walletconnect/web3-provider command and then added the following code to import into ...

Why does Material-UI TableCell-root include a padding-right of 40px?

I'm intrigued by the reasoning behind this. I'm considering overriding it, but I want to ensure that I'm not undoing someone's hard work. .MuiTableCell-root { display: table-cell; padding: 14px 40px 14px 16px; font-size: 0. ...

Is it possible to dynamically change the 'amount' on a PayPal button or iframe?

My task is to create a checkout page that exclusively uses PayPal for payment processing. The challenge I face is that the purchase amount is not fixed; users can input the desired amount for their purchase (e.g. buying a £100 gift code). PayPal typicall ...

Steps for creating a table with a filter similar to the one shown in the image below

https://i.sstatic.net/zR2UU.png I am unsure how to create two sub-blocks within the Business A Chaud column and Potential Business Column. Thank you! I managed to create a table with input, but I'm struggling to replicate the PUSH & CtoC Column for ...

The typescript MenuProvider for react-native-popup-menu offers a range of IntrinsicAttributes

Looking to implement drop-down options within a Flatlist component, I've utilized the React Native Popup Menu and declared MenuProvider as the entry point in App.tsx. Encountering the following error: Error: Type '{ children: Element[]; }' ...

Creating a Validation Form using either PHP or JavaScript

I need to create a form with the following columns: fullname, email, mobile, and address. If the visitor fills out the mobile field, they should only be allowed to enter numbers. And if the visitor fills out the email field, they should only be allowed to ...

Is it possible to log messages to the Selenium RC log using JavaScript in Selenium?

Seeking a way to log messages to Selenium RC's log using Javascript. For instance seleniumRc.log('Statement'); Wondering if it can be done? Appreciate any help! DashK ...

Is there a preferred method for looping through a NodeList and transferring its elements without the need to convert them into an Array?

Take a look at this jsFiddle that showcases the issue. It seems that while iterating over and making changes to the NodeList directly, the counter variable i skips every other node. In the provided fiddle example, there are two lists, #one and #two, and t ...