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

Tips for implementing Animation.css in Angular version 1.5.8

I have successfully added the ngAnimate dependency to my AngularJS project: var app=angular.module('testApp',['ngRoute', 'ngAnimate']); I have also included the animation classes in my animation.css file: .slide-animation.n ...

Avoid clicking in areas outside the perimeter of the blue circle in the SVG

Is there a way to restrict clicking outside the blue circle? The goal is to only allow opening by clicking on the svg itself, This includes everything, even white space inside the svg. How can this be achieved in the code? The current behavior is that ...

Interacting with Controller object externally in AngularJS

When declaring a controller using the following syntax: <div ng-app="scopeExample" ng-controller="MyController as ctrl"> <input id="box" ng-model="ctrl.num"> equals {{ ctrl.num }} </div> <script> angular.module('scope ...

When the page is refreshed, reorienting axes in three.js encounters difficulties

I am currently working on a project that involves using the three.js editor source code available for download on the three.js website. As part of this project, I am required to adjust the orientation of the axes to align with standard airplane coordinate ...

How can I update the chartjs instance?

I am currently working on creating a reactive graph that updates based on certain values. However, I am running into issues where my computed ChartData() function is not updating the component as expected. I have tried using the update() function, but I am ...

Utilizing node.js as a standalone web server application

I've developed a node.js-based web server (Javascript file) designed to serve a Javascript-integrated web page for controlling immersive sound on mobile devices. The server utilizes native modules for MIDI and pcap communication, along with express fo ...

Showing a gallery of images in React

I have a unique situation where I am working on setting a variable to match the import statement that calls for images. Once I have this variable assigned, I want to use it to display the corresponding image. For instance, if my code generates the name &ap ...

Looking to eliminate the bullet point next to the labels on a highcharts graph?

I have implemented a Highcharts solid gauge in my project, and you can view a sample image https://i.stack.imgur.com/QQQFn.png However, I am facing an issue where unwanted grey bullets are appearing in the test environment but not locally. I have checked ...

Utilizing Filters (Pipes) in Angular 2 Components without Involving the DOM Filters

When working in Angular 1, we have the ability to use filters in both the DOM and Typescript/Javascript. However, when using Angular 2, we utilize pipes for similar functionality, but these pipes can only be accessed within the DOM. Is there a different ap ...

In order to enable automatic playback of background images

Having created a slider with hover functionality on icons to change background images, I now seek to add an autoplay feature to the slider. The slider was implemented in a WordPress project using Elementor and involved custom Slider creation through JavaSc ...

Navigating the screen reader with the cursor位

Site Design Challenge I recently discovered that the master/detail design of my website is not very accessible. The main view features a column chart where each column represents a different month. Clicking on one of these columns reveals details in a nes ...

How can I integrate live data from a MySQL database to automatically update tables on a website?

I have developed a basic application using C# and .NET, with MVC architecture and a MySQL database linked to my server. I have utilized ADO.NET database models to automatically generate static data in my views from the models saved in the database, with ...

What is the best way to create a reusable component for this particular version of Autocomplete?

Can anyone help me figure out how to make this Autocomplete component reusable? I am using it multiple times but struggling with defining the necessary useStates. <Autocomplete required value={firstName} onChange={(event, newV ...

Take care of all default document types in the Html5ModeFeature plugin for ServiceStack

This snippet of code represents my first attempt at creating a ServiceStack plugin to support the angularjs configuration $locationProvider.html5Mode(true); when using ServiceStack in a self-hosted environment. This was a requested feature on Stack Overflo ...

Sending JSON data stored in a JavaScript variable through a jQuery POST request

I am currently attempting to retrieve data from a remote location using a JQuery post method. It works perfectly fine when I directly input the data to be posted, but for some reason, it fails when I store the JSON in a JavaScript variable and pass it in. ...

Display a modal popup form in ReactJS when a particular key is pressed

As a beginner in ReactJS, I am currently developing the frontend of a web application that requires multiple modal dialogues to be displayed based on specific key combinations. To achieve this functionality, I plan to utilize JQuery-UI for the modal dialog ...

Struggling with the proper state updating in React hooks when using dynamic naming conventions?

I am currently working with a react component that handles login requests to my server. This component is housed within a modal using Material UI. <TextField onChange={handleChange} autoFocus name="email" ...

What is the proper method for overriding styles in material-ui v5 for properties that are not present in the themes components?

Currently, I am customizing MuiDataTables using the adaptv4theme in the following manner: declare module '@material-ui/core/styles/overrides' { export interface ComponentNameToClassKey { MUIDataTable: any; MUIDataTableFilterList: any; ...

What is the process for verifying user authentication in a GET request?

My frontend utilizes Reactjs, while the backend is built with Nodejs and expressjs, connected to a Postgresql database. I have a basic signin page that authenticates users from the database. In my Reactjs application, once signed in, users can upload files ...

Issue with AngularJS: Local storage not saving updated contenteditable data

My local storage implementation stops working when I attempt to incorporate contentEditable feature. Here is the link to the CodePen for reference: https://codepen.io/zanderbush/pen/WNwWbWe. Any assistance would be greatly appreciated. The functionality w ...