Ensuring coherence between variables across various controllers in AngularJS

Within my controller, I have set up an interval to display the variable value on the view and count up:

$scope.value = 0;
var $higherScope = $scope;


interval = $interval(function () {

    $scope.value++; 

}, 1000);

Now, when opening a modal, I also want to display this variable counting up:

$modal.open({
        templateUrl: 'modal.html',
        backdrop: true,
        windowClass: 'modal',
        controller: function ($scope, $modalInstance) {

            $scope.value = $higherScope.value;

        }
    });

However, displaying the variable in this way does not show it synchronously with the original variable in the parent controller. Instead, it only displays the state of the variable at the time the modal was opened.

Is there a way to ensure that the variable is displayed in the modal as it updates in real-time in the parent controller?

Answer №1

One method involves storing your value in a shared service that is injected into both of your controllers.

UPDATE:

Here is a simple example using $interval (similar to what OP does) in SomeController to update the value displayed in AnotherController's view.

For clarity, you can check out the code here: http://plnkr.co/edit/UqZ7tUHTPXnjeBP8j4qF?p=preview

app.js:

var app = angular.module('plunker', []);

// For simplicity, I have included two controllers and a service/factory within this same file.
// Ideally, each should be in its own file ;-)


app.factory('valueService', function($interval) {
  var service = {
    value: 0,
  };

  return service;
});



app.controller('SomeController', function($scope, $interval, valueService) {
  $scope.name = 'Some Controller';

  start();      // This line will run when the constructor initiates, kicking off everything.

  function start() {
    $interval(function(){
      valueService.value++;   // This controller increments a value stored in the shared service (which the other controller uses to update its view)
    }, 1000);
  }
});


app.controller('AnotherController', function($scope, valueService) {
  $scope.name = 'Another Controller';
  $scope.valueService = valueService;
});

index.html:

<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>

  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1e7f7079607770603605x741541485577081247">[email protected]</a>" src="https://code.angularjs.org/1.3.13/angular.js" data-semver="1.3.13"></script>
  <script src="app.js"></script>

</head>

<body>
  <div ng-controller="SomeController">
    <p>{{name}}</p>
  </div>
<hr/>

  <div ng-controller="AnotherController">
    <p>{{name}}</p>
    <p>{{valueService.value}}</p>
  </div>
</body>

</html>

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

AngularJS Filter without creating a new object

Within my code, I am dealing with an array of objects that contain sub-objects. This particular array is utilized in an ng-repeat to display data in a table format. To illustrate, consider the following example: device { "name": "computer" ...

What is the best way to transfer a JSON object from an Express server to a Next.js page?

I am currently new to using Next.js and Express. My goal is to send post data from the server to the client, which in this case is my web browser. I have successfully received the data on the server, and now I need to send it to the corresponding page. Bel ...

Using callback functions to handle parameters in GET requests

Hey there, I'm currently diving into the world of callback functions and I have a burning question that needs clarification. Adding event listeners seems easy enough: $0.addEventListener("click", function(event){console.log(event)}); When you click s ...

How can I make the background image of an input text slide out of view when the "Enter" key is pressed?

The code is set up to slide out of view when the user clicks on the image, but I'm unsure how to make it do the same when the user hits "enter" in the input area. It's a bit frustrating... http://jsfiddle.net/mlynn/vxzc6z6y/ JavaScript code: ...

What could be the reason for the initial response appearing blank?

How can I retrieve all the comments of a post using expressjs with mongodb? I am facing an issue where the first response is always empty. Below is the code snippet: const Post = require("../models/posts"), Comment= require("../model ...

How to make an element vanish in Vue.js after a transition

My webpage features a notification system created with vue.js. Everything is functioning properly, but I am looking to remove the element once the transition has completed. Currently, I am achieving this using a setTimeout function, which is not the most e ...

The function assigned to [variable].onclick is not being executed, despite no errors being displayed in the console

I'm new to javascript and I'm looking for help with a simple task. I want to create a code that when clicking on an image, it will open in a modal. This feature is important for viewing full-size images on my portfolio. Although there are no erro ...

Optimal approach for reutilizing Javascript functions

After creating a simple quiz question using jQuery, involving show/hide, addClass, and tracking attempts, I am now considering how to replicate the same code for multiple questions. Would it be best practice to modify all variables in both HTML and jQuery, ...

Incorporating an external SVG link into a React application

While I may not be an SVG expert, I haven't encountered any issues with loading SVGs in my React app so far. I prefer using the svg tag over the image tag because sizing tends to present problems with the latter option when working with external links ...

What is the method to playback CENC-protected MP4 video by utilizing the HTML5 <video> element?

Trying to play a video that has been CENC-encrypted using MP4box with specific options: MP4Box -crypt drm_file_gpac_clear.xml BigBuckBunny.mp4 -out BigBuckBunny_cenc.mp4 The XML file contains clearKey encryption details, sourced from GPAC's website ...

AngularJs: uncomplicated rating system

Is there a way to increase a variable in an ng-repeat loop when clicked? <li class="item" ng-repeat="post in posts"> ... ... <button ng-click="incrementLike(post.like_count)">Like {{post.like_count}}</button> ... ... </li> $scope ...

Toggle between multiple chart displays within a <div> using a selection list

With around 20 div sections on my webpage, I encountered an issue where selecting option 1 and then 2 still displayed the chart of 1. Any tips on adjusting the JavaScript to ensure that charts are displayed correctly when changing selections in the list? W ...

Switch the URL back to its original form after decoding

Here is a URL that I need to decode in order to remove the %3AF%2, etc. http%3AF%2Fmo-d6fa3.ao.tzp.corp%3A3000%2Flogin%2Fcallback&client_id=x2.node"; To decode it, I use var decodedUrl = decodeURIComponent(url). After making some changes, I am now t ...

"Retrieve objects from an array based on specified minimum and maximum values, while also checking for any null

My current dataset is structured as follows: const data = [ { id: '11se23-213', name: 'Data1', points: [ { x: 5, y: 1.1 }, { x: 6, y: 2.1 }, { x: 7, y: 3.1 }, { x: 8, y: 1.5 }, { x: 9, y: 2.9 ...

Difficulty in displaying accurate visuals for Albers US Choropleth Map using d3.js and React

I'm currently troubleshooting my code as I'm only seeing a large square of one color when I attempt to create a colorScale for each element with the class "county" on this Albers US map. The desired outcome is something similar to this project: ...

Utilizing hyperlinks within NicEdit content and managing events with jQuery

I am using nicEdit, a rich editor, on my website to insert hyperlinks into the content. While I can successfully add hyperlinks using the setContent() method after initializing nicEdit, I am facing issues with handling click events for hyperlinks that have ...

Error with the jQuery scrolling plugin

Currently, the script is set up this way: jQuery(document).ready(function(){ var windheight = jQuery(window).height(); var windTop = jQuery(window).scrollTop(); var windbottom = windheight + windTop ; jQuery.fn.revealOnScroll = function(){ return this.e ...

Steps to access the $rootElement within the Angular root object

In my quest to locate the root element within a random Angular project with only the angular object available, I am aware that this is not the most conventional approach. However, I am willing to settle for a workaround solution. Initially, I attempted to ...

Does Somebody Possess a Fine Floating Tag?

Some time ago, I came across this floating label that I have been searching for ever since. I experimented with a few that appeared promising and initially worked well, but they ended up presenting their own issues. Some required the mandatory attribute f ...

A step-by-step guide on troubleshooting JavaScript/Typescript code in VSCode with Bun.sh

Recently, I delved into using Bun to execute typescript files without the need for compiling them to js. So far, my experience has been smooth sailing. However, when it came time for runtime debugging, I hit a roadblock as I couldn't find any informat ...