Changing the $scope value in one controller based on the input from a

I'm facing an issue with updating my side menu items based on user data. I have a side menu controller where I need to display the username, and in another controller where I retrieve user data from the database and want to update the menu items accordingly. I've tried using $watch and services but haven't been successful. I'm open to suggestions that don't involve using $rootScope as I'm not familiar with it.

.controller('menuCtrl', function($scope) {
    $scope.username = ""
})
.controller('afterloginCtrl', function($scope) {
var a = "this is username"      
$scope.username = a // here I wish to update username in menuCtrl
    })

If you require more code or further details, please let me know.

EDIT

The challenge lies in updating user information stored in the database table. I need to fetch the latest username and other info from the database and reflect these changes in the menu controller every time the data is updated.

Answer №1

If you need to share data between controllers, consider using a service for that purpose.
For instance:

.service('userData', () => ({info: {}, customMethod: () => {}}))
.controller('Controller1', (userData, $scope) => {$scope.user = userData.info;})
.controller('Controller2', (userData) => {userData.info.name = 'username';});

You can also enhance the service by adding relevant methods, and so on.

Subsequently, these methods can be utilized:

.controller('Controller2', (userData, apiService) => {
   apiService.fetchUser()
     .then(user => userData.setData(user));
});

Answer №2

.service('userAuthentication', () => ({}))

.controller('primaryController', (currentLoggedInUser, $scope) => {
  $scope.userData = userAuthentication;
})

.controller('secondaryController', (userAuthentication) => {
  userAuthentication.username = 'loggedInUsername';
})

Answer №3

When relying on services or factories, any data stored will be lost upon refreshing the page. However, a solution is to utilize browser session storage.

sessionStorage.setItem('NAME', "XYZ"); //store Data
sessionStorage.getItem('NAME'); // Retrieve Data

//Once you are done using the data, you can clear it from session storage.
sessionStorage.clear();

Answer №4

Utilize the power of localStorage to store data locally.

In your primary controller, insert this snippet of code:

localStorage.setItem($scope.username);

Then, in the subsequent controller:

$scope.username = localStorage.getItem();

Answer №5

According to the feedback provided above, it seems that your requirement is to ensure that the username persists even if the user closes the app and reopens it. However, using a service or factory may result in data loss once the app is reloaded or closed.

Solution :

You can utilize the localStorage to store the username and access the data across different controllers.

Sample Code :

You can create a shared factory service that will save and retrieve the stored local storage data based on the specified key.

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

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

In the controller :

To set and retrieve data from the local storage, inject the storageService dependency into the controller.

.controller('menuCtrl', ['$scope','storageService',function($scope,storageService) {
    // Retrieve local storage data using storageService
  storageService.get('username');
}])
.controller('afterloginCtrl',['$scope','storageService',function($scope,storageService) {
    var a = "this is username"      
    // Save local storage data using storageService
    storageService.set('username', a);
}])

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

How can I store items in a JavaScript array so that they are accessible on a different page?

I'm running into an issue with my PHP website. Each item has a "request a quote" button that, when clicked, is supposed to add the item name to an array using JavaScript. This array should then be added to the "message" field on the contact.php form. ...

Error encountered when attempting to upload image on Twitter: missing media parameter

According to the latest Twitter media upload API documentation, it is recommended to first utilize either POST multipart/form-data or base64 encoded files when interacting with . However, encountering an error with code 38 stating "media parameter is mi ...

Trouble with innerHTML in a for loop when using getJSON

My current challenge involves displaying a series of JSON results within a div tag using innerHTML. <script> $(document).ready(function() { var html2 = ''; var thread_id = ''; var created_thread_ids ...

Displaying a pair of values using a single noUISlider

I'm trying to achieve something unique with a noUIslider range by outputting two values. While I've managed to display the same value twice using examples from the noUIslider documentation, my goal is to have one of the outputs show a value that ...

Dynamic binding in AngularJS with ng-repeat allows for seamless updating of data

I recently started using a helpful library called Angular Material File input <div layout layout-wrap flex="100" ng-repeat="val in UploadDocuments"> <div flex="100" flex-gt-sm="45"> <div class="md-default-theme" style="margin-le ...

Issue with ReactJS: onChange event does not function properly when value is changed using jQuery

This is the reactjs code I am working with: <input name="date" id="date" value={this.state.listManage.date} onChange={this.handleForm} type="text" /> When I manually type in the input field, the onChange function works ...

Easily iterate through the <li> elements using jQuery and append them to the <datalist> dynamically

My jQuery loop seems to be malfunctioning as it's not showing the values of my li elements. Instead, I'm seeing [object HTMLElement] in my input search bar. <div id="sidebar-wrapper"> <input type="text" list="searchList" class="searc ...

Oops! An error occurred while trying to load the myApp module. The module 'ui.bootstrap' is missing and causing the failure

When using Firefox, I encountered the following error: SyntaxError: syntax error xml2json.js:1 SyntaxError: syntax error ui-bootstrap-tpls-0.13.0.js:1 Error: [$injector:modulerr] Failed to instantiate module myApp due to: [$injector:modulerr] Failed to in ...

Is there a way to make a try-catch block pause and wait for a response before moving

I've been successfully retrieving data from my Firestore database, but I've encountered a major issue that I can't seem to resolve... Whenever I click the "Read Data" button, I have to press it twice in order to see the console log of the d ...

Removing data from the controller with JQUERY AJAX in a Spring MVC application

Could someone assist me with this issue? I am trying to implement ajax and sweetalert.js using the following repository: So far, everything is working well when I use onclick = "" to call my function. However, I need guidance on how to properly utilize th ...

Error: The node is unable to parse JSON data through the API

After loading a JSON file as a string, attempting to parse it back to JSON and send it as a response: router.get('/todos', (req,res) =>{ let todos = fs.readFile('todos.json', 'utf8',(err, data) =>{ if (err) ...

Are elements loaded and hidden by ng-hide and ng-show, or does loading only occur with ng-show?

Is this method of programming effective for handling large elements such as 10 mb images? Are there alternative solutions that would work better? ...

How to address additional attributes received from the server in Next.JS

Encountering an error while trying to render a canvas with specified height and width within a child component in a NextJs app. The issue arises when attempting to integrate this mouse effect into my NextJS application. Everything functions correctly until ...

Which is better: specifying Node.js version with nvmrc or in package.json engines

Ensuring that other developers working on my JavaScript project use specific versions of node and npm is important to me. I recently added the following code snippet to my package.json file: "engineStrict" : true, "engines": { "node" : "10.10.0", ...

What is the best way to define a variable in EJS?

I need to populate my database array results on the frontend using EJS. The code snippet I'm using is as follows: var tags = ["<%tags%>"] <% for(var i=0; i<tags.length; i++) { %> <a href='<%= tags[i] %&g ...

Issue with sending functions to other components in Angular

I'm currently facing an issue with passing functions to other objects in Angular. Specifically, I've developed a function generateTile(coords) that fills a tile to be used by leaflet. This function is located within a method in the MapComponent. ...

Troubleshooting a NextJS and ExpressJS error related to on-demand entry pinging

A challenge arose as I implemented NextJS with a custom server using Express. The issue surfaced while defining routes in Express. Defining Express routes as shown below resulted in errors: app.get('/:username', handle.profile) app.get('/: ...

The jQuery dropdown selection for only displaying the month and year is not functioning properly when using the select

Currently, I am utilizing a datepicker with only the month and year as options to select from using dropdowns. However, when I apply the following CSS to disable the days of the datepicker, it ends up affecting all datepickers in my JSP file. 1. Is there ...

Node.js promises are often throwing Unhandled Promise Rejection errors, but it appears that they are being managed correctly

Despite my efforts to handle all cases, I am encountering an UNhandledPromiseRejection error in my code. The issue seems to arise in the flow from profileRoutes to Controller to Utils. Within profileRoutes.js router.get('/:username', async (r, s ...

Express.js encountering an `ERR_HTTP_HEADERS_SENT` issue with a fresh Mongoose Schema

My Objective Is If data is found using the findOne() function, update the current endpoint with new content. If no data is found, create a new element with the Schema. Issue If there is no data in the database, then the first if statement throws an ERR_H ...