Transferring a variable from one function to another within the same controller

In my controller, I am defining a variable called tst and assigning it a value in a function named GetOrders. However, when I try to access the tst variable in another function called GetTotalValueOfProducts, it is returning as undefined without a value. This is the code snippet I am using:

<script>
 app.controller('OrderController', function ($scope, $http) {
    $scope.quantity = 1;
    $scope.Orders = {};
    var tst ;
    GetOrders = function () {
        $http.get('/Order/GetAllOrders').success(function (response) {
            $scope.Orders = response;
            //I confirm that 'tst' has a value assigned here
            tst = response;

        });
    }
    GetOrders();

    GetTotalValueOfProducts = function () {
       //however, at this point 'tst' is showing up as undefined
        var p = tst;

    }
    GetTotalValueOfProducts();
  });
 </script>

Can you identify what might be causing this issue?

Answer №1

One common reason for this issue is the asynchronous nature of JavaScript.

The problem arises when you call GetOrders(), which makes an HTTP request that will take some time to complete. Before this request finishes, you are calling GetTotalValueOfProducts, resulting in it being undefined.

<script>
 app.controller('OrderController', function ($scope, $http) {
    $scope.quantity = 1;
    $scope.Orders = {};
    var tst ;

    GetTotalValueOfProducts = function () {
       //but here 'tst' is undefined!!!
        var p = tst;

    }

    GetOrders = function () {
        $http.get('/Order/GetAllOrders').success(function (response) {
            $scope.Orders = response;
            //here i set tst, and tst has value, i checked it has value and it's not undefined
            tst = response;
           GetTotalValueOfProducts();

        });
    }
    GetOrders();



  });
 </script>

The above code snippet should produce the expected result. Make sure to consider when to call the function based on your requirements.

Answer №2

Greetings! AngularJS operates asynchronously, meaning that GetTotalValueOfProducts(); is being invoked before the success callback has returned any value from http. It's important to execute your function only after the callback has finished.

To achieve this, you can utilize $q from AngularJS. Check out more information about it here: $q

Answer №3

The scenario you're facing is a common challenge in JavaScript asynchronous programming. The second function often runs before the promise from the initial function gets fulfilled.

Answer №4

To ensure accurate calculations, it is recommended to invoke

  GetTotalValueOfProducts();

within the success callback of the $http service. Modify your code as follows:

 <script>
     app.controller('OrderController', function ($scope, $http) {
       $scope.quantity = 1;
       $scope.Orders = {};
       GetOrders = function () {
         $http.get('/Order/GetAllOrders').success(function (response) {
           $scope.Orders = response;
           GetTotalValueOfProducts(response);
        });
       };
      GetOrders();

      GetTotalValueOfProducts = function (tst) {
        var p = tst;
      };

     });
  </script>

Answer №5

Insert the tst variable into your internal $scope object. UPDATE It was careless not realizing that these functions are asynchronous. You should retrieve your results like this:

Insert the tst variable into your internal $scope object. UPDATE It was careless not realizing that these functions are asynchronous. You should retrieve your results accordingly.

app.controller('OrderController', function ($scope, $http) {
  $scope.quantity = 1;
  $scope.Orders = {};
  $scope.tst;
  GetOrders = function () {
      $http.get('/Order/GetAllOrders').success(function (response) {
          $scope.Orders = response;
          $scope.tst = response;
          GetTotalValueOfProducts();
      });
  }
  GetOrders();

  GetTotalValueOfProducts = function () {
     //but here 'tst' is undefined!!!
      var p = $scope.tst;
  }

});

Alternatively, consider using $q

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

jquery ajax not ready - responsetext empty - status code 0 - statustext error occurred

I encountered an error message stating: jquery ajax readystate 0 responsetext status 0 statustext error when providing this URL: url(http://www.tutorialspoint.com/prototype/prototype_ajax_response.htm), however, the same code works perfectly fine with thi ...

employing strings in passing functions as arguments

The script below, taken from a tutorial by Adam Khoury, is designed to create a timer that displays a message once it reaches completion. While I grasp the overall functionality of the code, I'm puzzled by the use of strings in certain parts: 1) Why ...

Please be patient for the function to complete its execution

I am currently facing a challenge where the execution of functionA needs to halt until functionB() has provided an answer. In this case, the duration for functionB to respond varies depending on user input, ranging from 1 second to up to 10 seconds. As a r ...

Develop a dynamic thunk and additional reducer to efficiently handle multiple API calls and retrieve data

Using Redux and Redux-Toolkit, I aim to streamline my code by implementing a single asynchronous Thunk and extra reducer for multiple requests. Below is the setup for both the company and client slices: import { createSlice, createAsyncThunk } from &apos ...

The AngularJS DOM seems to be updating, but the screen is not reflecting any changes. Uncertain about the next steps to take

I am experiencing a perplexing issue where, despite ng-click updating the expected scope variables and the changes being visible in the DOM via the Chrome debugger, the altered DOM elements are not redrawn in the browser. This anomaly occurs consistently o ...

How can I prevent the button from being triggered by keyboard input?

I have styled a button using the following CSS class: .disabled{ pointer-events: none ; opacity: 0.6 ; } Despite being disabled, I can still interact with it dynamically through JavaScript. However, my issue arises when using the keyboard to reac ...

The page keeps scrolling to the top on its own, without any input from me

Whenever I reach the bottom of the page, my function loads new items seamlessly. However, an issue arises when the new items load, causing the scrolling position to abruptly return to the top of the page. This disrupts the user experience and is not the de ...

Adding additional text will not render d3.js' output

I'm struggling with a simple issue here, My goal is to add a div to my svg element containing text. I have written the code for this and in the DOM, it shows that the svg has the correct class attached along with the desired text. However, the text i ...

Ways to refresh page in AngularJS

We are utilizing an MVC application with AngularJS for the front-end. The menu view contains the following code snippet: <ul> @foreach (var child in parent.Children) { <li class="@MenuHelper.SetChildClass(child, ViewBag) childNode"> ...

Having trouble importing NPM packages (e.g. Faker) in TypeScript?

Currently I am encountering an issue while attempting to import Faker into my project. The file structure is as follows: import * as faker from 'faker'; interface Test { FirstName: String, LastName: String } function create() { le ...

What is the method in the Node URL module to set multiple search parameters simultaneously?

It appears that there is a way to set parameters in the URL like this: myUrl.searchParams.set('param1', 'value'); myUrl.searchParams.set('param2', 'value'); ... However, I would prefer to do something more concise, ...

Angular directives for Kendo UI

I have been working with Angular 1.5.* in conjunction with Kendo UI. I have followed all the steps outlined in the documentation on the Telerik site, including: Ensuring that the kendo scripts and styles are included Adding kendo.directives to my angular ...

Forward user to a subdomain once they have successfully logged in on an Angular 2 application

I've been working on an Angular 2 application and I'm looking to redirect users from www.example.com to admin.example.com after they successfully log in. What is the best way to accomplish this using Angular 2? Additionally, how can I test this f ...

Incorporating Checkbox Value into Textbox with classic ASP and jQuery

Here is a glimpse of the code I've written: response.write "<th align=left><font size=2>" response.write "1. <input type=checkbox class='checkboxes' value='ORG'>Organization" response.write "</font> ...

Combining the results of two JavaScript range sliders to calculate commissions

I am currently working on developing a commission calculator with sliders. My goal is to have two sliders that can show the sum of their values combined. Although I have managed to get both slider outputs, I am struggling with converting them into a total ...

What is the best method for saving HTML form data into a Node JS variable?

I am facing an issue with setting the values of HTML form inputs onto my Node JS variables. In the JavaScript code below, I am struggling to assign values to the variables "hostname" and "port," which should then be concatenated to create a new variable ca ...

Two separate tables displaying unique AJAX JSON response datasets

As a beginner in javascript, I am facing a challenge. I want to fetch JSON responses from 2 separate AJAX requests and create 2 different tables. Currently, I have successfully achieved this for one JSON response and table. In my HTML, I have the followi ...

Parameterized Azure Cosmos DB Stored Procedure

I am currently learning about Azure Cosmos Db, and I am in the process of developing a simple JavaScript stored procedure that will return a document if a specific Id is provided. However, when I run the stored procedure, I do not receive a "no docs foun ...

I am getting an undefined response when attempting to retrieve documents from a database using Mongoose

My goal is to develop a function that takes two arguments, username and email. If either of them is already in the database, the user should not be able to register. function checkAll(username, email) { let num = 0; User.find({}, (err, result) => { ...

How can a JS script determine the shape of a quadrilateral based on its properties?

Hi there! I'm new to coding and could use some guidance. I've been given a task to create a script that takes input for the length of each side and the angles of each corner in order to determine whether the shape is a square, rectangle, rhombus ...