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

How can I update the version of v8 in NodeJS to ensure I have the latest Javascript enhancements?

Is it possible to upgrade the JavaScript engine version from 3.x to 6.x without updating the Node.js version? The current Node version is 0.12.x. ...

How to stop Mouseenter event from bubbling up in an unordered list of hyperlinks using Vue 3

I've experimented with various methods to prevent event bubbling on the mouseenter event, but I'm still encountering an issue. When I hover over a link, the event is triggered for all the links as if they were all being hovered over simultaneousl ...

Getting the click event object data from a dynamically created button with jQuery or JavaScript

I have a task of tracking page button click events. Typically, I track the objects from statically created DOM elements using: $('input[type=button]').each(function () { $(this).bind('click', function () { ...

What steps should I take to create code that can generate a JWT token for user authentication and authorization?

I'm struggling to get this working. I have a dilemma with two files: permissionCtrl.js and tokenCtrl.js. My tech stack includes nJWT, Node.js/Express.js, Sequelize & Postgres. The permission file contains a function called hasPermission that is linke ...

Icon Searchbar Feature in Ionic 2

I am currently working with Ionic2 and have integrated the ion-searchbar component into my project: https://i.sstatic.net/CqmF4.png Question Would it be possible to customize the search icon? The default icon is a magnifying glass, but I would like to r ...

Node.js is throwing GitHub API 401 Bad Credentials error, whereas curl is not encountering the

I am attempting to authenticate on Enterprise GitHub using @octokit/rest. When I execute the following Curl command, I receive a list of API URLs: curl -u "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80edf9c0e5ede1e9ecaee3e ...

Using the .ajax() function with jQuery to retrieve data and then using .find() on that data

Currently I am facing an issue while trying to extract the body tag from the result of the .ajax() call. Instead of getting the desired result, I only see undefined logged into the console... This is the section of code causing the problem: $(document).r ...

AngularJS lazy loading for a Bootstrap carousel slider

I am looking to implement lazy loading in Bootstrap CAROUSEL similar to this example: example <img data-lazy-load-src= However, I am using ng-src (AngularJS) to fetch images in the slider. How can I modify this example to work with an Angular Boots ...

Is there a way to retrieve the values of a checkbox from a location outside the form where it is initially defined?

After successfully developing a script that deletes rows from a table when a checkbox is selected, I encountered an issue where the values of the checkboxes were not accessible outside of the form action they were placed in. The checkboxes and correspondin ...

How can I prevent duplicate IDs when submitting a form through AJAX within a while loop?

While submitting a form using Ajax within a while loop, I encountered an issue where the same form ID is being used multiple times due to the loop. As a result, the form only submits once. I believe that I need to generate a unique ID for each iteration of ...

How to disable a specific array of dates in Ant Design range picker

Is there a way to block dates prior to the current date and specify certain dates that should also be disabled on the calendar? For example, I need to prevent selection of: Today: 2018-07-30 Dates to disable: [2018-08-10, 2018-08-12, 2018-08-20] When t ...

The setTimeout function appears to be malfunctioning

I've encountered an issue where a webpage keeps scrolling endlessly without stopping. I've attempted to terminate it by using the exit function, but unfortunately it's not working. Does anyone have a solution for this problem? ...

Oops! You can only have one parent element in JSX expressions

I'm working on creating a password input box, but I keep encountering an error when integrating it into my JS code. Here's the snippet of my code that includes TailwindCSS: function HomePage() { return ( <div> <p className=&q ...

Employing angularjs alongside a static jsonp file produces results on the first attempt

Currently, I have data being retrieved from a jsonp file within my application. worm.factory('simpleFactory', function ($http, gf) { var simpleFactory = ""; return { getJson: function ($scope) { var url = 'myfile.json?callback=J ...

Having issues with Npm installation not finishing up. Can anyone provide a solution to rectify this

I've been waiting for 30 minutes and my upload is still not completed. How can I resolve this issue? Click here to see the problem ...

Ways to clear the Yeoman index.html cache

Every time I update my Angular app, the old version continues to show up, requiring a "hard" refresh on the browser as a workaround (which is not ideal). My project uses Yeoman (generator-angular) and after examining the Gruntfile.js, I noticed that it re ...

mention a Vue.js component computed property that points to a specific DOM element

Is there a way to access the DOM element that initiated a method inside a Vue component computed property? For example: <template> <img :src="getUrl" class="image1"/> <img :src="getUrl" class="image2"/> </template> <scri ...

Add different input strings to an array within the scope when there is a change in the input value (AngularJS)

My goal is to populate an empty array within the scope with strings. The number of elements in this array can vary depending on what the user types in the player count input field. $scope.playerNames = []; To achieve this, I am using a $watch function th ...

What could be causing my Vue.js sorting array script to malfunction?

I'm encountering an issue with sorting the table by Date. The sort function used to determine the type of sorting no longer works, and I'm unsure why. html: <th @click = "sort('data_produktu')" class="date">Da ...

Creating a basic bar graph using d3.js with an array of input data

In my dataset, I have an array of form data that includes items like 'Male', 'Female', 'Prefer Not To Say'. I want to create a simple bar chart generator using D3.js that can display the percentages or counts of each item in t ...