Utilizing variable values in Google Charts with AngularJS

Hello everyone, I am attempting to display a chart using data obtained from an API. The output of the API is in the form of List<String> and not in JSON format. Here is the snippet of my JS file:

google.load('visualization', '1', {
packages: ['corechart'] 
});


app.controller("chartController",function($scope,$http)
    {


$http.get("/idcountcisco")
.success(function(data){

    $scope.cisco=data
    console.log($scope.cisco)


})


    $http.get("/idcountlog4j")
.success(function(data){

    $scope.log4j=data
    console.log($scope.log4j)


})
    $http.get("/idcountwin")
.success(function(data){

    $scope.windows=data
    console.log($scope.windows)


})



if (($scope.cisco=!undefined )&&($scope.log4j=!undefined )&&($scope.windows=!undefined ))

{

var data = google.visualization.arrayToDataTable([
                                                  ['type', 'Qs' ],
                                                  ['cisco', $scope.cisco],
                                                  ['lo4j',$scope.log4j ],
                                                 ['windows',$scope.windows],
   ]);
var options = {
  title: 'Statistiques'
 };
 var chart = new    google.visualization.PieChart(document.getElementById('chartdiv'));

 chart.draw(data, options);

}

});

Upon checking the console log, the values retrieved are:

$scope.cisco=18
$scope.log4j=45
$scope.windows=15

However, the displayed chart does not seem to reflect the real values as all variables become equal to true after the conditional statement.

I appreciate any assistance or guidance on this matter.

https://i.stack.imgur.com/LszGy.png

Answer №1

There are actually two issues to address in your code:

The first issue:

In your code, you used =! instead of !=. So when you wrote $scope.cisco=!undefined, it set true to $scope.cisco which is '!undefined'. This causes your if condition to always be true.

It should be

if (($scope.cisco!=undefined )&&($scope.log4j!=undefined )&&($scope.windows!=undefined ))
or you can use angular.isUndefined to check if the variable is undefined or not.

The second issue:

You are making all the $http.get requests in your controller and trying to draw a chart before all the requests finish executing. Since $http.get runs asynchronously and returns a promise, there is no guarantee that all get requests will complete before reaching your if condition. This is the second issue that needs fixing.

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

Retrieving information and implementing condition-based rendering using React's useEffect

I am currently developing a MERN stack application that retrieves information regarding college classes and presents it in a table format. The CoursesTable.js component is structured as follows: import React, { useState, useEffect } from 'react'; ...

Is there a way to duplicate an image a specified number of times depending on a given output value?

As a beginner in coding, I am looking to learn how to dynamically insert multiple images based on input and output values. Currently, my code for basic addition looks like this: <form oninput="x.value=parseInt(a.value)+parseInt(b.value)"> <inpu ...

Difficulties encountered when initiating CRA using npm start

Hi everyone! I'm dealing with a frustrating issue; every time I try to run npm start I keep encountering the error message below: events.js:288 throw er; // Unhandled 'error' event ^ Error: spawn cmd ENOENT To resolve this probl ...

Is there a difference in performance between using multiple inline scripts versus one combined inline script?

Comparing Multiple Inline Scripts to a Single Conjoined Inline Script: <script type="text/javascript">/* some codeblock 1 */</script> <script type="text/javascript">/* some codeblock 2 */</script> <script type="text/javascript"& ...

Difficulty Encountered in Rendering Component Using setTimeout Function

Having trouble figuring out why my component, enclosed in a setTimeout function, is not appearing on the DOM: const ContentMain = Component({ getInitialState() { return {rendered: false}; }, componentDidMount() { this.setStat ...

Enhancing serialized form with additional information through an ajax request

I'm currently facing an issue with adding additional data to my serialized form string. The situation is that I have a form with a set of fields called "Services", and users are able to add as many services as they want dynamically using a button in t ...

The image selection triggers the appearance of an icon

In my current project, I am working on implementing an icon that appears when selecting an image. The icon is currently positioned next to the beige image, but I am facing difficulties in making it disappear when no image is selected. Below are some image ...

Devices such as CAC cards and smart cards are not being recognized by Chrome's WebUSB feature

I recently developed a script to identify all USB devices connected to Chrome using chrome.usb.getDevices. Surprisingly, the script successfully detected a second-generation iPod touch, a mouse, keyboard, and two unidentified items from Intel. However, it ...

Expanding the boundary with Material-UI: Tips for stretching the margin

I am currently working on creating a navigation bar using Material UI, and the current layout can be seen in the image below. https://i.stack.imgur.com/AOy3v.png While following the template provided by MUI documentation, I encountered an issue with alig ...

Employing a script that is generated from the jQuery AJAX response

How does using script as the response for a jQuery/AJAX request benefit us? Is it possible to directly run a function from that response script after sending the AJAX request? Any simple examples would be much appreciated. ...

Make real-time edits to JavaScript code on a webpage

Is there a method aside from using Firebug in the DOM view to edit live JavaScript embedded within an HTML page? For example, code like this within a .html file: <script type="text/javascript> // code here </script> Thank you. ...

There seems to be an issue with AppModule in your code. The error message states that it is not recognized as an NgModule and the problem

After upgrading to node 6, angular 4, typescript 2.3.2, and @angular/cli 1.02, I meticulously followed the steps outlined in the Guide for updating @angular/cli. I will include my entire package.json below in case there are any relevant details. The specif ...

What is the process for activating namespacing on a VueX module that has been imported?

I am currently utilizing a helper file to import VueX modules: const requireModule = require.context('.', false, /\.store\.js$/) const modules = {} requireModule.keys().forEach(filename => { const moduleName = filename ...

Is there a way to automatically change the value of one input box to its negative counterpart when either of the two input boxes have been filled in?

Consider two input boxes: box1 box2 If a user enters a number in one of the input boxes, we want the value of the other input box to automatically change to the opposite sign of that number. For example: User enters 3 in box1. The value of box2 shoul ...

Control the playback of individual HTML5 audio elements using jQuery for seamless user experience

How can I modify the code to ensure that only one HTML5 audio element plays at a time? Currently, all tracks are able to play simultaneously. I am using jQuery for play and pause functionalities. If one track is playing and another is clicked on, how can ...

Guide to creating intricate designs on an HTML5 Canvas, one pixel at a time

Imagine a scenario where there is a 900x900 HTML5 Canvas element involved. In this case, there is a function named computeRow, which takes the row number as a parameter and returns an array of 900 numbers. These numbers represent colors ranging from 0 to ...

I'm having trouble retrieving data from the server using the AngularJS $http.get() function. What am I doing wrong

Ensure that your question is clear and that your code properly showcases the issue at hand. Feel free to leave any questions or comments below for clarification. app.js var express = require('express'); var app = express(); app.use(express.sta ...

What are the reasons behind the failure of this regex matching in Angular specifically on Safari browser?

In my angular project, I have the following code. It works perfectly fine in Chrome and Firefox, but in Safari, it throws an exception. var shour = "9:00:00 PM CDT"; var ehour = "12:00:00 AM CDT"; var conver_shour = shour.match(/^(\d+):(\d+)/)[ ...

Unable to eliminate the string "C:fakepath" using JavaScript's replace function and regular expressions

I've been struggling for quite some time with this issue. Let me share a snippet of the code that's causing trouble: jQuery(':file').change(function() { var path = jQuery(this).val(); var filename = path.replace(/C:\\ ...

The way an event can be outrun or vanish due to another event

let bar = new function(){ $scope.MessageSpan="Item added successfully";} When the Add button is clicked, the above function is invoked. However, if I want to hide this message when any other button is clicked, I would have to update the span text for all ...