Develop a feature to allow users to update their screen name upon logging in through angularjs

I am developing a node.js web application with angularjs for the client side.

Upon user login, I need to save their username and link it to an element on the webpage.

Instead of using session storage, is there an alternative method to store this information?

In my template page, the element is displayed as follows:

<div class="header">
<h3 class="text-muted">This is a template</h3>
<ul class="nav navbar-nav navbar-right">
    <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Username here<b class="caret"></b></a>
        <ul class="dropdown-menu">
            <li><a href="#">Settings</a></li>
            <li><a href="#">Profile</a></li>
        </ul>
    </li>
</ul>

Should I create a controller method for the template page that will call a service in my app.js file to retrieve the username?

Answer №1

Strategy

My suggestion is to implement a Factory as an AngularJS Service for this task. Utilize this Factory to retrieve User information from an API and save it as a JSON object. By accessing the Factory in your controller, you can easily extract the necessary details such as the username.

Since each AngularJS service acts as a Singleton, you can be certain that only one instance containing the User information exists at any given time.


Code Snippet

Service (Factory):

app.factory('UserService',
  function($http) {
    // This is where a RESTful API resource can be invoked,
    // a JSON object stored in the application scope,
    // and then returned by the service to any controller.

    return {
      getUsername: function() {
        return "tjhack"
      }
    };
  });

Controller:

app.controller('MainCtrl', function($scope, UserService) {
  $scope.username = UserService.getUsername();
});

Live Example

http://plnkr.co/edit/wma66tx6FefzrjzprwUN?p=preview

Answer №2

Watch this insightful video https://www.youtube.com/watch?v=62RvRQuMVyg by the Google Double Click team as they tackle challenges while developing an Angular App. They demonstrate how they efficiently send user information from the server and store it in Angular.

In a nutshell: embed user details as a JSON payload within the HTML document, then utilize a service to manage and retrieve this data.

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

Encountering a TypeError with Arg 1 while trying to execute the save method in jsPDF

I am currently working on a react project with a simple implementation of jsPDF. I am trying to execute the sample 'hello world' code but encountering an error when using the save method: https://i.stack.imgur.com/o4FWh.png My code is straightf ...

Creating a Discord Bot: Building an Embed Table/List with Segmented Sections

Currently in the process of learning Javascript and venturing into discord.js, I'm fully aware that the code I am working with is not up to par and requires some serious refinements. The main objective here is to split up the arguments of a command a ...

Handling Errors with Symfony 5 JSON Responses and VueJS Using Axios for Customized Error Messages

I need to show a personalized error message when my JSON response throws an error. Some of my services trigger an error like this: if (count($recipients) === 0) { throw new TransportException($this->carrierService::ERROR_NO_MAIL_ADDRESSES); } The ...

Implement a dynamic table in real-time with jQuery AJAX by fetching data from JSON or HTML files

Hey @SOF, I'm trying to add an auto-update feature to my school grades webpage using jquery and ajax to refresh the data when new information is available. I also want to create a "single view" for classes. The challenge I'm facing is getting t ...

Having trouble loading a JSON object into a Datatable using Jquery?

I am currently utilizing DataTables in combination with Jquery. I have a data source in the form of an JSON object that I intend to retrieve via Ajax and showcase within the table. The JSON data is retrieved from the /live/log url and has the following fo ...

Route parameters do not function correctly with computed properties

I'm facing an issue with my getter function that stores all products. When I try to retrieve a single product dynamically based on this.$route.params.id, it doesn't return any value. The code works fine when I navigate to a specific product, but ...

Using Javascript to organize information into a table with multiple columns

I'm looking to format a table using data retrieved from an ajax call, but I'd like the data to appear in columns instead of rows. Here is the code for the table body: <tbody id="tableData-marketMonth"> <tr> <th>Lead ...

Is it possible to share an .ics file using SparkPost in a Node.js environment?

Attempting to generate an i-cal event and link it to a sparkpost transmission in the following manner: const event = cal.createEvent({ start: req.body.a.start, end: req.body.a.end, summary: req.body.a.title, description: req.body.a.body, ...

Encountering a technical issue with Highstock code showing error code

I combined two time series in highstock, but upon running the sample code, I encountered Highcharts error #15 in the console. Additionally, the browser did not display properly. Despite checking that the time series data is in ascending order, I cannot det ...

Adding various textures to an obj file

I am trying to add a texture to my obj file but encountering an error message. Below is the snippet of code I'm using: new THREE.MTLLoader() .setPath( 'models/cool' ) .load( 'CobbleStones.mtl', func ...

Numerous social media sharing buttons conveniently located on a single webpage

Currently, I am working on a research database project where the goal is to allow users to share articles from the site on various social networks such as Facebook, Twitter, LinkedIn, and Google+. To achieve this, I successfully implemented share buttons ...

How can I protect my .js file with sensitive database information from being accessed by users in Node.js?

Currently, I am utilizing Node.js in conjunction with Socket.io. Within my project, there exists a file named service.js which holds important MySQL connection details. The issue at hand is that by simply entering www.mysite.com/service.js into the browse ...

Tips for adjusting the maximum characters per line in tinyMCE 5.0.11

I have an angular 8 application that utilizes tinyMCE, and I am looking to limit the maximum number of characters per line in the textArea of tinyMCE. My search for a solution has been unsuccessful so far despite extensive googling efforts. (image link: [ ...

Having trouble importing discord.js in typescript

Currently in the process of converting my Discord Bot from JS to TS, I've stumbled upon a roadblock. Attempting to write it like this just won't seem to work import { Message } from 'discord.js'; However, when I write it like this, ev ...

Success is returned as AJAX error

My AJAX call is returning an error as Success instead of a JSON error from ASP.NET MVC. Can someone please advise on how I can resolve this issue? Thank you. [HttpPost] public JsonResult Register(int EventID) { try { ...

Chrome Extension: Step-by-Step Guide to Disabling Page Visibility API

Currently, I am in the process of developing a Chrome extension that requires the capability to prevent webpages from triggering the document visibilitychange event. My main objective is to find a way to override the read-only property of document.visibili ...

Show the project directory path using Gulp-Notify in the terminal instead of revealing the entire project location on the hard drive

Currently, I am utilizing gulp-notify to enhance the information displayed in the terminal during task execution. However, at the moment, it only shows the full path on my hard drive along with the file name. I believe that displaying only the project fold ...

Ways to extract the value from a jQuery object

How can I retrieve the selected time value using a jQuery plugin and save it on a specific input element within the page? Refer to the plugin and code provided below: http://jsfiddle.net/weareoutman/YkvK9/ var input = $('#input-a'); input.cloc ...

Formatting Dates in Node.js

Can someone assist me in understanding how to properly format the print date shown below? Thu Sep 06 2018 18:18:26 GMT+0530 I attempted to use console.log(new Date()) However, the output generated was 2018-09-06T12:48:25.776Z I am unsure of how to co ...

What is the best way to access information from my table and utilize it in a popup window?

Currently, I am developing a table that displays selected values from my database. I have made the rows clickable to open a Popup as shown in the example. However, I am facing issues with getting the values from my selected row into the popup for further ...