Bidirectional data binding with Angular salutations

Forgive me for asking what may seem like a simple question. I am currently working on a demo quiz project using Angular. The first page features a basic two-way data binding greeting (where you input your name and it displays a welcome message, e.g.

<p> Welcome {{name}} </p>

I'm wondering how I can save the entered name and carry this welcoming message over to the next page/template. Here is a snippet of the code:

<strong>Welcome</strong> {{email}}

  <p class="lead">Please enter your name </p>
      <body ng-app ng-init="email = 'John';">
      <label>enter name<input type="text" ng-model="firstName"/></label><br />
  </body>

Here is the routing setup:

'use strict';


angular
  .module('angularQuizApp', [
    'ngAnimate',
    'ngCookies',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch'
  ])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .when('/about', {
        templateUrl: 'views/about.html',
        controller: 'AboutCtrl'
      })
      [...]

I began with a yeoman angular scaffold so I haven't made many changes yet. Thank you in advance, knowledgeable Angular experts!

Answer №1

To easily achieve your desired outcome, consider developing a service that can store the user's name:

angular.module('angularQuizApp').
 factory('StorageService',[
function(){

    var name = "";

    var _setName  = function(name){
        name = name;
    }:

    var _getName = function(){
        return name;
    };  

    return {
        setName : _setName,
        getName : _getName,
    }

}]);

In your controllers, utilize the appropriate methods from the service:

angular.module('angularQuizApp').
controller('MyController', ['$scope', 'StorageService',
   function($scope, StorageService) {
     $scope.name = StorageService.getName(); // or setName(name_value)
}]);

This service will retain the user's name throughout your angular application. You have the flexibility to save other data within this service as well. However, please note that this data will be lost once you exit the app.

If you require persistent storage for objects, consider using angular-storage: https://github.com/grevory/angular-local-storage

EDIT

Check out this functional demo app that I created: http://plnkr.co/edit/7ZzBYnKmV1xflzi81YQc?p=preview

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

Use Cypress to make requests to GraphQL endpoints using the .request method

Despite my efforts to search for information on using Cypress requests with GraphQL, I come across terms like "mock up server" and "stub" without a clear example. I am struggling to find a comprehensive guide on how to effectively utilize GraphQL with cy ...

Only allow scrolling if the number of child elements exceeds a certain limit

I am looking to implement a scroll feature on the <ul> element when the number of <li>s exceeds a certain threshold. For example, if we have 12 children, I want to display only 7 of them and then scroll through the rest. This is my current app ...

Display SVG at full size without any distortion

How can I make the SVG image 100% by 100% without scaling? I want the image to be centered on the page both horizontally and vertically. The challenge is that I also want to display the areas outside of the SVG artboard, so using CSS to center it won&apos ...

Export a specifically designed object from a module using Python

When working with node.js in JavaScript, you can set module.exports = 13; in a file called module.js, and then import it elsewhere using x = require("module.js");. This will directly assign the value of 13 to variable x. This method is useful when a modul ...

Protractor - Issue with Page Object not reflecting changes in DOM elements

Currently, I am conducting testing on a Single Page Application created with angular.js. For test writing, I am following the Page Objects pattern. Within this application, there are several lists that undergo updates. For instance, there is a list of atta ...

Can you please provide a detailed list of all the events that are compatible with the updateOn feature in Angular's ngModelOptions?

The reference documentation notes the following: updateOn: a string that specifies which event should be bound to the input. Multiple events can be set using a space delimited list. There is also a special 'default' event that aligns with the ...

Using ternary operators in a return statement is not effective when working with the react useState Hook

Struggling to make sense of my framework code and trying to refactor the business logic, I find myself in a state of confusion as things are not functioning as expected. Currently, I have successfully implemented a simple counter in React using the useStat ...

Having trouble retrieving information from an external local json file

I'm attempting to display an 'alert' box containing text retrieved from a JSON file. However, I'm facing issues in fetching data from the JSON file and the alert box is not being displayed. var thebook = JSON.parse(book); function s ...

Oops! An error occurred: fs.readFileSync is not a valid function to perform the Basic

I'm facing a dilemma - I have a relatively simple app (I'm still new to Node): App.js import * as RNFS from 'react-native-fs'; var config_full; // readFile(filepath: string, encoding?: string) RNFS.readFile('./config.toml', ...

Error message encountered: "myData undefined while executing server in Node.js"

const express = require('express'); const app = express(); app.post('/', (req, res) => { let newData = new contact(req.body); newData.save() .then(() => { res.send("Data has been successfully saved to ...

Disregard Cloudflare's Automatic RocketLoader feature for certain JavaScript scripts

After extensive research and failed attempts, I am seeking help to disable Cloudflare Rocketloader for a specific JavaScript file on my WordPress website. Specifically, I need to exclude the Automatic Rocket Loader for a particular .js file. I attempted t ...

Transitioning the style code from inline to the head of the document disrupts the straightforward JavaScript intended to

As I delve into the world of web development, I encountered a simple issue that has been causing me frustration for the past hour. It involves code to display the border color of a div element using an alert. The code works perfectly fine when the style is ...

Steps to send an asynchronous AJAX request to the server-side within the JQuery validation plugin using the addMethod() function

Currently, I am in the process of developing my own framework using the JQuery validation plugin to validate CRUD forms both client-side and server-side. It is crucial that these forms are not static but rather created dynamically using "handlebar.js". Fo ...

Measuring the pixel distance of scrolling on a page with overflow hidden

I am trying to implement a functionality where a class is toggled for the body element on a page with hidden overflow and single screen, based on the amount of scroll. However, there is a challenge: the scrolling behavior involves animation rather than act ...

What is the method for altering the color of the webkit-slider-thumb using JavaScript?

I am looking to adjust the color of an input range using JavaScript instead of CSS. Can someone help me with this request? Current CSS Code: input[type='range']::-webkit-slider-thumb { -webkit-appearance: none; background: goldenrod !importa ...

The latest update to andt version 5.20.0 has encountered an issue with the FastColor.js file located in the node_modules. An error has been identified at line 56

After updating to the latest version of [email protected], I utilized npm i antd --save --legacy-peer-deps without any issues. However, upon running npm start, I encountered an error in the console. Is anyone else experiencing this problem? ERROR in . ...

Issues with Vercel Next.js environment variable functionality not functioning as expected

I integrated Google Maps into my Next.js project successfully while working locally. The secret key for Google Maps is stored in next.config.js and accessed in the code through process.env.NEXT_PUBLIC_GOOGLEMAPS After deploying the project to Vercel, I de ...

Are there any jQuery Context Menu plugins clever enough to handle window borders seamlessly?

After reviewing UIkit, as well as some other jQuery Context Menu plugins, I have noticed that they all tend to exhibit a similar behavior: The actual menu div renders outside the window, causing valuable content to be hidden from view. Is there a way to ...

Using Angular's ng-style directive to apply various styles based on multiple conditions and attributes

I am attempting to apply multiple styles to an accordion group using the ng-style directive since ng-class is not compatible with accordions. Here is my current implementation: ng-style="{ border: ivrMessageForm.ivr_messagetitle.$error.required && ...

Executing a query in MongoDB to retrieve data from multiple collections simultaneously

Currently, I have two separate collections for different types of products. My goal is to retrieve all documents from both collections that belong to a specific user. I am aware that I could achieve this by running 2 queries for each collection, merging t ...