passing data between functions using a shared global variable within an angular controller

Having some difficulty passing a value from one function to another within an Angular controller.

I have an event:

onTimeRangeSelected: function (args) {
          $scope.dayPilotCal.clearSelection();
          $scope.createNewEventModalWindow(args);
      },

The event calls the function:

 $scope.createNewEventModalWindow = function(args)
    {
      console.log('create new event dialog');
      $rootScope.newEvent.start = args.start.value;
      console.log($rootScope.newEvent.start);
      ngDialog.open({
          ......
      });

    }

Then, I handle the dialog confirm button click event:

 <button
      type="button"
      class="ngdialog-button ngdialog-button-primary"
      ng-click="btnCreateEventClicked()"
    >Create</button>

And call the function:

$scope.btnCreateEventClicked = function(){
  console.log('btn create event clicked');
  ngDialog.close();

  console.log($rootScope.newEvent.start);
};

My problem is that in the first case

console.log($rootScope.newEvent.start);
prints the real date to the console. However, in the second function
console.log($rootScope.newEvent.start);
prints 'undefined' to the console.

All the code resides in the same controller. At the beginning of the controller, I define my global variable $rootScope.newEvent={};

If anyone could assist me with this problem, it would be greatly appreciated. Thank you.

Answer №1

Testing code becomes challenging when global variables are used because any function can access the global scope. It seems like there may be another part of your code that modifies $rootScope.newEvent.

If this variable needs to be accessible globally, consider using a service instead.

If there is no requirement for this variable to be accessible globally, simply update $rootScope.newEvent to $scope.newEvent.

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

Adding client-side scripts to a web page in a Node.js environment

Currently, I am embarking on a project involving ts, node, and express. My primary query is whether there exists a method to incorporate typescript files into HTML/ejs that can be executed on the client side (allowing access to document e.t.c., similar to ...

How to activate a function or event upon closing a browser tab with JavaScript

How can a function be triggered when a user closes the browser tab, preventing it from closing immediately and instead displaying a popup prompting the user to either proceed to another page or close the tab? Scenario: In the event that a user attempts t ...

Instructions for returning a function from within another function and then displaying it upon return

My current state: constructor(props) { super(props); this.state = { temperatureConversion: '', Here is the function I'm using: handleChange = async (value) => { this.setState({ value }); await Axios.ge ...

Troubleshoot: Unable to utilize mapActions with Vuex modules

Having trouble using mapActions to reference actions in my modules. The Vuex docs say that module actions are not namespaced by default, so they should be accessible like main store actions. Here's how I have things set up: Store import * as ModuleA ...

How can I enhance the functionality of AJAX in Symfony 1.4 when using jQuery, specifically in cases where a select box's options depend on the selection of another select box?

In my Symfony 1.4 application, I have three interconnected tables outlined below. Table 1: Conflictos1: connection: doctrine tableName: conflictos_1 columns: id: type: integer(4) fixed: false unsigned: false primary: tru ...

Vue-bootstrap spinbutton form with customizable parameters

I am in need of a custom formatter function for the b-form-spinbutton component that depends on my data. I want to pass an extra argument to the :formatter-fn property in the code snippet below, but it is not working as expected. <b-form-spinbutton :for ...

Disabling the onClick event on HTML tags with personalized WooCommerce messages

I have customized the notices/success.php template file by modifying the content as shown below: <?php foreach ( $messages as $message ) : ?> <div class="woocommerce-message" role="alert"> <span> <?php ...

How can I showcase a module constant in HTML using Angular JS?

Within my module, I have a constant defined as follows: angular.module('SampleMod',[]) .constant("VERSION", "2.1"); I am looking for a way to display the constant value in HTML using something like this: <p>{{VERSION}}</p> Is ther ...

Implementing AngularJS HTTP basic authentication using a username and password to access the Pivotal Tracker API

I am currently working on developing an application to access Pivotal Tracker stories. My first step is to implement basic authentication in order to retrieve my Pivotal Tracker token. With PHP cURL, I have been using the following command: curl -X GET - ...

When accessed through jQuery, the WebAPI Controller will route to a plain JSON view

I am encountering a strange issue with my ASP.NET MVC application. When calling a WebAPI controller through jQuery's $.get method, everything works fine until the callback function finishes. Instead of seeing my web page, I am redirected to a raw JSON ...

The initial state in Next.js does not support accessing localStorage

I'm currently working on a project using Next.js along with Redux Toolkit. Initially, I attempted to utilize localStorage, but encountered the issue 'localStorage is not defined'. As a result, I switched to using cookies-next, only to face a ...

Is there a type-safe alternative to the setTimeout function that I can use?

When running my tests, I encountered an issue with the setTimeout method making them run slower than desired. I initially attempted to address this by using "any" in my code... but that led to complaints from eslint and others. Now, I have implemented a ...

Encountering an issue with npm installation in the angular-phonecat tutorial: Module 'update-notifier' not found

Having trouble running npm install in the angular-phonecat directory. Could be a problem with my paths, but I'm not certain. Any help would be greatly appreciated. Keep running into Error: Cannot find module 'update-notifier'. If I try to in ...

Creating a captivating animation for a social media like button with CSS

I came across some animation code on the web and noticed that when I click the image, it replays the animation from the starting point. I want to make it so that when I click the image, the animation plays and stops, and if clicked again, resets the image. ...

How come my dynamic source path doesn't function correctly unless I add an empty string at the end of it?

Recently, I encountered an issue while using Vue.js to dynamically create a source attribute using an object's properties. Here is the code snippet where I faced the problem: <img :src='"../assets/" + project.image.name + "." + project.image. ...

Guide to ensuring jQuery Ajax requests are fully processed with WatiN

Currently, I am in the process of developing WatiN tests to evaluate an Ajax web application. However, I have encountered a timing issue with Ajax requests. My main objective is to ensure that WatiN waits for the Ajax request to be completed before valida ...

The largest contentful paint is anticipating an unidentified event

My website is encountering issues with Google Pagespeed and I'm unsure of the cause. The primary bottleneck appears to be the LCP time, which Google reports as taking between 7 and 11 seconds during each test. Upon analyzing the waterfall chart, it ...

Easy navigation in AngularJS

I have created two files in Angular for a simple Login application. The first file is Login.html: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> AngularJS Login SPA</title> < ...

Leveraging PrismJS within an Angular application

I am currently implementing prismjs in my Angular app Here's what I have so far app.directive('nagPrism', [function() { return { restrict: 'A', transclude: true, scope: { source: '=&a ...

Encountering a display issue within a port using Express

Recently, I enrolled in an advanced ExpressJS course. While exploring the course website, I stumbled upon the "hello world" section. Intrigued, I decided to copy and paste the code provided below: const express = require('express') const app = ex ...