AngularJS scope variable not getting initialized inside promise

I've encountered an issue with my code while using CartoDB. The goal is to execute a query using their JS library and retrieve some data. The problem arises when I attempt to assign the result as a scope variable in AngularJS, after successfully working inside the done() function. Here's a snippet of the code. EDIT: My apologies for the confusion earlier. By saying "doesn't work", I meant that I always receive the default value of mvcTotal = 0, instead of the computed value from the JavaScript.

angular.module('angMvcApp')
  .controller('DataCtrl', ['$scope', '$routeParams', function ($scope, $routeParams) {
    var borough = $routeParams.borough;

    var sql = new cartodb.SQL({user: 'wkaravites'});
    var table = 'qiz3_axqb';
    var mvcTotal = 0;

    if (borough != null) {
      $scope.borough = borough;
    } else {
      $scope.borough = "Data Overview";

      sql.execute("select borough, count(*) from qiz3_axqb group by borough")
        .done(function(data) {
          $.each(data.rows, function(index, value) {
            console.log("pizza: " +value['count']);
            mvcTotal += value['count'];
          });
          console.log(mvcTotal +" totals");

          $scope.mvcTotal = mvcTotal;

        })
        .error(function(errors) {
          console.log("errors:" + errors);
        });
      console.log(mvcTotal+" test test");

      $scope.mvcTotal = mvcTotal;

      #scope.mvcTotal = 57;

    }


  }]);

Is there an error in how I'm assigning a regular variable to an Angular scope variable? In the JS console, I can see the log with pizza and the correct number followed by "totals."

Below is the HTML view:

<div class="container">
  <div class="row">
    <div class="col-lg-12">
      <h1>{{borough}}</h1>
      <p>{{mvcTotal}} motor vehicle collisions</p>
    </div>
  </div>
</div>

Answer №1

To ensure proper handling of data retrieved from your database query, it is essential to perform any operations inside the 'done' function. While you may be aware of this concept, understanding the sequence in which code is executed is crucial. Utilizing a debugger can help visualize the flow:

var sql = new cartodb.SQL({user: 'wkaravites'});

//step #1
var mvcTotal = 0;

  //step #2
  sql.execute("select borough, count(*) from qiz3_axqb group by borough")
    .done(function (data) {
      //step #6 This section is executed after receiving a response from the database call. At this point, mvcTotal remains at 0.
      //$scope.mvcTotal is set to 57
      $.each(data.rows, function (index, value) {
        console.log("pizza: " +value['count']);
        mvcTotal += value['count'];


      });
      //step #7 The correct total is now displayed
      console.log(mvcTotal +" totals");

      //step #8 Displaying the calculated total in the HTML view using {{mvcTotal}}
      $scope.mvcTotal = mvcTotal;

    })


  //step #3 mvcTotal still retains its initial value of 0
  console.log(mvcTotal+" test test");


  //step #4 Since the DB call is still ongoing, mvcTotal remains at 0
  $scope.mvcTotal = mvcTotal;

  //step #5 The previous value was 0, but has now been updated to 57
  $scope.mvcTotal = 57;

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

Transmit information via ajax and receive responses in json format

Looking to send a string and receive JSON format in return. The current method is functional but lacks the ability to return JSON code. $.ajax({ url: "getFeed.php", type: "post", data: myString }); Attempts to retrieve JSON string result in ...

Add content or HTML to a page without changing the structure of the document

UPDATE #2 I found the solution to my question through Google Support, feel free to read my answer below. UPDATE #1 This question leans more towards SEO rather than technical aspects. I will search for an answer elsewhere and share it here once I have th ...

External CSS File causing improper sizing of canvas image

I have been working on implementing the HTML5 canvas element. To draw an image into the canvas, I am using the following javascript code: var img = new Image(); var canvas = this.e; var ctx = canvas.getContext('2d'); img.src = options.imageSrc; ...

Tips for sending information to a JavaScript variable through AJAX requests

Hello there, I'm currently working on a project that involves posting data stored in a JavaScript variable using AJAX. Can anyone assist me with the correct syntax for this process? <div class="container-fluid"> <div class="card shadow m ...

What is the optimal number of parameters in JavaScript?

After stumbling upon a question on StackOverflow discussing the number of parameters in JavaScript functions (How many parameters are too many?), I started pondering if there is a real limitation on how many parameters a JS function can have. test(65536 ...

transform array elements into an object

I encountered the following code snippet: const calcRowCssClasses = (<string[]>context.dataItem.cssClasses).map( (cssClass) => { return { [cssClass]: true }; } ); This code block generates an array of objects like ...

Is it possible to include an if/else statement within a tailwind class in React components?

I want to dynamically change the background color of a div based on a condition. If the condition is true, I want the background color to be white; otherwise, I want it to be black. Despite trying to achieve this using an if/else statement, the background ...

swap out a JavaScript function for a fresh function

In our ordering system, there is a hidden function that I cannot access. Interestingly, this function contains a spelling error which causes a grammar issue to appear in a popup when a user interacts with it. Is there any way for me to either modify the t ...

What is the best way to send extra parameters to an ajax callback function?

Currently, I am implementing an ajax call in the following manner: util.AjaxCall(url, successCallbackFunction, errorCallbackFunction); function successCallbackFunction(result) { // Result returned from Ajax } Although everything is functioning correc ...

What is the best way to create a command that updates the status in Discord using discord.js?

I'm currently working on a command for my Discord bot using discord.js. The purpose of this command is to change the bot's status whenever an admin of the server triggers it. I've attempted to create the command, but unfortunately, it's ...

Can you help me understand how to ensure the CSS translate feature lands in a specific div, no matter its initial position?

I'm facing a roadblock in my journey to create a card game. The issue arises at the final stage of the Translate function implementation. In this game, the player is dealt 30 cards (I've simplified it to four for ease of programming), and upon cl ...

Unexpected alteration of property value when using methods like Array.from() or insertAdjacentElement

I'm encountering an issue where a property of my class undergoes an unintended transformation. import { Draggable, DragTarget } from '../Models/eventlisteners'; import { HeroValues } from '../Models/responseModels'; import { Uti ...

Developing a feature to organize content by categories and implement a functionality to load more data efficiently using NodeJS routes

I am looking to develop a system that limits the number of displayed posts and includes a "load more" button to retrieve additional posts from where the limit was previously reached. Additionally, I want to implement the functionality to change the orderin ...

Rendering illuminated component with continuous asynchronous updates

My task involves displaying a list of items using lit components. Each item in the list consists of a known name and an asynchronously fetched value. Situation Overview: A generic component named simple-list is required to render any pairs of name and va ...

The content of XMLHttpRequest is accessible via the property response

Typically, when we want to retrieve data using AJAX, we would use code like this: var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ elem.innerHTML = xhr.responseText; ...

Using jQuery to display a div after a 2-second delay on my website, ensuring it only appears once and does not reappear when the page is refreshed or when navigating to a

I manage a website that includes a blog section. Every time someone visits the site, I want a popup window to appear. (To achieve this, follow these steps - Utilize jQuery for showing a div in 5 seconds) I would like this popup to only be displayed once ...

How can you animate the background of a website using AngularJS - CSS or JavaScript?

My aim is to create a dynamic animation for the background image when the view changes. The current background image is set through a function defined within MainController: // app/js/controllers.js $scope.getBg = function() { return $route.current.sco ...

Importing a file using its absolute path in JavaScript

Within the dependencies directory, there exists a module named foo: import foo from '../dependencies/foo'; // This import statement works as intended The challenge arises when attempting to import from a different path due to deployment in an AW ...

What is the best way to retrieve EXIF data following the AJAX loading of images?

Currently, I am developing a swipe-able wine image viewer for NapaWapa.com and it's functioning quite smoothly: The challenge I'm facing is related to using a jquery plugin to extract the exif data from the images in the gallery. Unfortunately, ...

Is it possible to utilize a CSV file to dictate which images should be utilized on my website as a guide?

I'm currently working on my website's gallery and have a collection of over 60 images. I'm exploring ways to streamline the process of displaying these images by having the website read their names from a CSV file instead of manually coding ...