Transferring information among various instances of a single controller (ng-controller)

I am relatively new to using Angular and I am facing a challenge with a seemingly simple task that is proving to be more complex within the framework.

The issue at hand involves data manipulation, specifically with a variable named var1. I am modifying this data in one section of the webpage while needing to display it in another section.

<body ng-app="app">
    <div id="div1" ng-controller="TestCtrl">
        <input type="text" ng-model="var1" /> Var1: {{ var1}}
    </div>
    <br />
    <div id="div2" ng-controller="TestCtrl">
        Var1: {{ var1 }}
    </div>

 //..

I have initialized the variable within the controller as follows:

 angular.module('app', [])
    .controller('TestCtrl', function($rootScope){
        $rootScope.var1 = 1;
        $rootScope.var2 = 2;

        this.updateValues = function() {
            srv.updateValues($rootScope.var1, $rootScope.var2);
        };

    });

The issue arises when attaching the ng-controller to multiple divs, creating separate instances of the controller. This results in the second instance not recognizing the data modifications made in the first instance.

How can I access the var1 value from the first controller in another section of the webpage?

https://plnkr.co/edit/XgIWFW89tavnjOW09TBp?p=preview

  • One potential solution that comes to mind is attaching the TestCtrl to the body, ensuring only one instance of the controller exists for the entire webpage. Is this a common practice? It seems like a majority of my controllers may end up attached to the body tag.

  • I have come across the suggestion of using services, however, I am struggling to see how to implement a service for this specific scenario.

  • Are there any other solutions available?

Answer №1

Alright, let's dive into Miško's statement:

"..if you use ng-model there has to be a dot somewhere. If you don't have a dot, you're doing it wrong.."

To simplify, when you initialize var1 in the second controller, you are essentially creating your own scope (even with $rootScope).

Instead of directly accessing $rootScope:

$rootScope.var1 = 1;

It's better to utilize an object:

$rootScope.dataObj = {var1: 1};

https://plnkr.co/edit/oVB16H0PBLFx3PyLhuRN?p=preview

For more insights, check out:

Why don't the AngularJS docs use a dot in the model directive?

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 maintain the consistent speed of the Javascript timer even when the .deck is clicked?

Currently, I'm working on creating a memory card game. In this game, the deck of cards is represented by the class .deck. Strangely enough, every time I click on a card, the timer starts to speed up instead of keeping a consistent pace. How can I tack ...

Having trouble storing data accurately in local storage using React

I implemented a combination of useContext and useEffect to store useContext data in local storage, but I am facing challenges due to conditional rendering. The scenario involves displaying a sign-in button when the user is not logged in and a log-out butto ...

call a custom form submission using jquery first, followed by a regular form submission

Is it possible to attach a submit() handler to a form in order to execute an ajax request, and then have the form submit itself normally once the request is complete? Using $('#myForm').submit() seems to just result in the same function being cal ...

Interfacing with Ajax to dispatch information to a PHP script

Hello, I'm currently working on implementing Ajax in my web application. However, I've encountered a small issue. I'm attempting to check if a username has already been registered by controlling a form. The problem arises when my JavaScript ...

What is the best way to incorporate a unique font with special effects on a website?

Is there a way to achieve an Outer Glow effect for a non-standard font like Titillium on a website, even if not everyone has the font installed on their computer? I'm open to using Javascript (including jQuery) and CSS3 to achieve this effect. Any sug ...

If the condition has a class name of condition, then display

Having performance issues due to slow data rendering with each tab using a partial view. The code snippet for each tab is as follows: <div class="tab-content" ng-controller="MyController"> <div id="tab-1" class="tab-pane fade active in " ng-i ...

Managing JavaScript promise rejections

What is the best approach to managing an error, such as the one labeled "new error" in the code snippet below, that occurs outside of a promise? function testError() { throw new Error("new error") // How can this error be properly handled? var p ...

Encountering an issue with Meteor and node-celery: "Unable to access property 'slice' of null"

Check out the Github repository for reproducing this issue Run localhost:3000 to replicate the problem. In my setup with Meteor 1.4.4.1, I am utilizing the node-celery npm packages on the server side. Upon Meteor initialization, the client automatically i ...

Repetitive attempts have led to the cancellation of the AJAX and PHP petition statuses

Whenever I click the button, I am trying to update a MySQL table using AJAX jQuery. Unfortunately, I am encountering a problem where the AJAX jQuery does not work properly sometimes. It starts off fine, but after a certain number of attempts, it stops work ...

How to retrieve data obtained from parsing readline and fs in node.js beyond the scope of the callback function

This specific question diverges from the one mentioned with an existing answer. It pertains to a snippet of code taken from node.js documentation involving the use of fs and readfile, with a focus on detecting an end-of-file flag, which appears to be the r ...

styling multiple elements using javascript

Recently, I created a jQuery library for managing spacing (margin and padding). Now, I am looking to convert this library to pure JavaScript with your assistance :) Below is the JavaScript code snippet: // Useful Variables let dataAttr = "[data-m], [d ...

Adding jQuery content to a div that is being created dynamically

Currently implementing a save/load feature using JSON for a diagram that utilizes jsPlumb. While the save functionality is working perfectly, the load functionality is encountering difficulties in replicating the full initial saved state. The issue arises ...

Use JavaScript to sift through an array and exclusively retrieve items that match a specific value

I am working with an array of objects that contain a phase key, and I want to filter out only the ones that have a specific phase value. Additionally, I need to map some other key/value pairs into the final return. Here is my current code: phaseToBlocks ( ...

Google's geolocation.getCurrentPosition function fails to function properly on mobile devices after the page is refreshed

I recently created a website that utilizes the Google Geolocation JavaScript API along with the vue2-google-maps package. Here is a snippet of the relevant code: `geolocate () { var self = this this.loading = true navig ...

Setting up dynamic routing in AngularJS for links

I am facing some confusion regarding routing in AngularJS. Normally, we can configure routes in angular.config() when the angular module is loaded. At that time, we define static information such as routePath, templateUrl, and controller. However, I am u ...

What could be causing the function to not execute before the rest of the code in the React App?

My lack of expertise may be the reason, but I'm unsure how to address this issue: Here's what I have: A button labeled "Check numbers" <Button fullWidth variant="contained" onClick={this.checkOptOut ...

Rounding up the cents area using JavaScript

So, imagine this scenario: I'm inputting a dollar amount into a text field using code similar to this: <input type="text" name="qtr-revenue-<?php echo $qtr ?>" id="qtr-revenue-<?php echo $qtr ?>" class=&quo ...

What is the best way to transfer information between pages using onclick in node.js and express?

script1.js const database = new Datastore('database.db'); database.loadDatabase(); app.get('/api', (request, response) => { database.find({},(err,data)=> { if(err){ response.end(); return; ...

Using the Ajax method from a separate class in TypeScript: A step-by-step guide

Recently, I started learning about typescript and ajax. One of the challenges I encountered was while creating a method in typescript for making ajax calls that can be used across classes: myFunc(value: string): JQueryPromise<any> { var dfd = $. ...

Experiencing issues with exporting <SVG> file due to corruption

I received some downvotes on my previous post, and I'm not sure why. My question was clear, and I provided a lot of information. Let's give it another shot. My issue is with exporting <SVG> files from an HTML document. When I try to open t ...