Guidance on loading JSON array information into highcharts using AngularJS

I am working on a project in Play Framework (play-java) where I need to display a bar graph using Highcharts. The Java API returns data in JSON format with a field called 'name' containing values like 'Data', 'Gadgets', 'Others,' etc. I want the x-axis of the chart to display these values from the JSON array returned in response.

Below is the code snippet for handling the response in JavaScript:

for(var i=0; i<response.data.result.length; i++)
{
    $scope.total = $scope.total + parseInt(response.data.result[i].item_price);
}
var j = 0;
console.log(response.data.result);
while(j < response.data.result.length)
{
    $scope.jsonArray = [{
        name: response.data.result[j].category_name,
        y: (parseInt(response.data.result[j].item_price)/$scope.total)*100,
    }];
    $scope.renderChart();
}

The following code snippet is used to create the bar graph:

$scope.renderChart = function()
{
    Highcharts.chart('container', {
        chart: {
            type: 'column'
        },
        title: {
            text: 'Your Expenses'
        },
        subtitle: {
            text: 'Your total spent money is '+$scope.total+'.'
        },
        xAxis: {
            type: 'category'
        },
        yAxis: {
            title: {
                text: 'Money spent in percentage'
            }
        },
        legend: {
            enabled: false
        },
        credits: {
            enabled: false
        },
        plotOptions: {
            series: {
                borderWidth: 0,
                dataLabels: {
                    enabled: true,
                    format: '{point.y:.1f}%'
                }
            }
        },

        tooltip: {
            headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
            pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
        },

        series: [{
            name: 'Categories',
            colorByPoint: true,
            data: $scope.jsonArray
         }]
    });
}

I understand that using a while loop in the response code is not advisable. I would appreciate any help on how to ensure the y-axis calculates the percentage value correctly. My goal is to generate 'names' for the x-axis and percentage values for the y-axis of the chart. Thank you in advance.

Answer №1

To begin, make sure to set the jsonArray as empty before starting the loop. Use a for loop to go through each item in the array and assign the values correctly. Here is the updated code:

$scope.jsonArray = [];
            for(var i=0;i<response.data.result.length;i++)
            {
                $scope.jsonArray[i]={
                    name:response.data.result[i].product_name,
                    y: (parseInt(response.data.result[i].item_price)/$scope.sumTotal)*100,

                }
                $scope.generateChart();
                console.log(response.data.result[i]);
            }

    console.log($scope.jsonArray);
    })

Thank you for your help!

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

What is the best way to send objects to Angular when bootstrapping?

When initializing my main page where Angular will be bootstrapped, I will already have a user information object generated by my application (containing fields such as 'isLoggedIn' and 'username'). I find it unnecessary to load Angular ...

Is there a way to selectively include a filter in ng-repeat within a directive?

Utilizing an element directive across multiple views, the directive iterates through each 'resource' in a list of resources using ng-repeat="resource in resources". Different page controllers determine which resources are fetched from the API by ...

tips for generating a random number for direct display

Can anyone help me figure out how to automatically display the total of numbers from this script on my blog post without having to click anything? Additionally, I need it to update if the browser is refreshed. ` http://jsfiddle.net/BenedictLewis/xmPgR/ ...

Is there a way to sustain audio playback even after the current track has finished?

I am facing an issue with my code where I am trying to play the next song in a playlist or album after the current one finishes playing. Although I was able to get a song to play, it does not progress to the next one automatically. Below is the snippet of ...

Tips for avoiding the display of the overall scrollbar while utilizing grid with an overflow:

In my react-redux application, I am utilizing the material ui Grid component for layout design. The structure of my code is as follows: <div> <Grid container direction="row" spacing={1}> <Grid item xs={3}> ...

Comparing response times between AngularJS $http and $.ajax callbacks

I am puzzled as to why AngularJS $http service's success callback is giving me a slower response time compared to the $.ajax success callback. I ran this code 5 times with different JSON files: if(isJquery){ $.ajax({ type : 'GET', ...

Issues with click events in the navigation menu

How can I make my menu close when clicking on other parts of my website, instead of opening? I know that I should use a click event for this, but when I implemented a click event, my menu encountered 2 unwanted problems: 1- Whenever I clicked on a menu i ...

Using an AngularJS array with ng-repeat

As soon as a websocket message is received, the code below executes: connection.onmessage = function (eventInfo) { var onConnectionMessage = JSON.parse(eventInfo.data); if (onConnectionMessage.messageType === "newRequest") { getQuizRequests(); } } T ...

Passing PHP values to JavaScript and then to AJAX requires using the appropriate syntax and techniques for

Currently, I am populating a table with data retrieved from my database. Here is a snippet of the code: <?php //mysqli_num_rows function while($row=mysqli_fetch_array //I know this may be wrong, but that's not the point echo "<tr><t ...

Change the boxShadow and background properties of the material-ui Paper component

I am currently referencing their documentation found at this link in order to customize default Paper component properties. Below is the code snippet I have: import { styled } from '@mui/material/styles'; import { Modal, Button, TextField, Grid, ...

How can we determine the total character count of a file that has been loaded into a textarea

I have a textarea where I can count the number of characters as I type. function calculateCharacters(obj){ document.getElementById('numberCount').innerHTML = obj.value.length; } <textarea name="textField" id="my_textarea" class="text_edit ...

The unexpected behavior in React's reconciliation process: What is causing the state to remain unchanged?

While exploring the React documentation, I came across an interesting example of resetting state: here To better understand it, I created different sandboxes to experiment with. However, I am struggling to reconcile what I observe in each of them. Each s ...

Unlimited Possibilities in Designing Shared React Components

Seeking the most effective strategies for empowering developers to customize elements within my React shared component. For example, I have a dropdown and want developers to choose from predefined themes that allow them to define highlight color, font siz ...

display a new feature immediately upon the user's login

I encountered a scenario where the user is supposed to log in, and upon successful login, another component should be displayed. However, this functionality is not working as expected for me. I have to click the login button again or refresh the page to vi ...

How can you optimize the storage of keys in JS objects?

Just pondering over this scenario: Consider a line definition like the one below, where start and end are both points. let ln = { s: {x:0, y:0}, e: {x:0, y:0}, o: 'vertical' } Now imagine having a vast array of lines, how can we sav ...

What is the best way to add an element conditionally within a specific Vue Component scope?

I've been working on creating a Component for titles that are editable when double-clicked. The Component takes the specific h-tag and title as props, generating a regular h-tag that transforms into an input field upon double click. It's function ...

I am experiencing an issue where components are constantly re-rendering whenever I type something. However, I would like them to

Currently, I am in the process of developing a REACT application that takes two names, calculates a percentage and then generates a poem based on that percentage. The issue I am facing is that whenever I start typing in the input fields, the LovePercentCon ...

Is it possible to compile a TypeScript file with webpack independently of a Vue application?

In my Vue 3 + Typescript app, using `npm run build` compiles the app into the `dist` folder for deployment. I have a web worker typescript file that I want to compile separately so it ends up in the root of the `dist` folder as `worker.js`. Here's wha ...

A guide to accessing REST services in AngularJS using basic authentication

I currently have a REST service up and running on my server. Using Chrome Postman, I am able to access this service with Basic Authentication. However, I now want to build a user interface in AngularJS to display the data received from the REST service. T ...

I am looking to showcase images beside individuals' names or photos on my website in a vertical arrangement, similar to how it is done on Facebook

Looking for suggestions on how to display images uploaded by users on my webpage in a way similar to Facebook, with the user's photo displayed beside each image. Any recommendations or website links would be greatly appreciated. Thanks, Santosh Sahu ...