Creating a column chart with dynamic data in Angular using Highcharts

I have successfully integrated high charts in angular js using hard coded data. However, I am facing an issue when trying to display dynamic data fetched from a web service. In my controller:

$scope.months = [];
$scope.retail = [];
$scope.wholesale = [];

$scope.fetchChart = function(){
    $scope.chartConfig = {
        title: {
            text: ""
        },
        options: {
            chart: {
                type: 'column'
            },
            plotOptions: {
                series: {
                    stacking: ''
                }
            },
            legend: {
                layout: 'vertical',
                align: 'topleft',
                verticalAlign: 'top',
                borderWidth: 1
            }
        },
        xAxis: {
            categories: $scope.months
        },
        credits: {
            enabled: true
        },
        series: [{
            name: 'Retail',
            data: $scope.retail
        },
        {
            name: 'Wholesale',
            data: $scope.wholesale
        }
        ],

        loading: false
    }
};

$http.get(http://localhost:8080/abc/pqr/mno/getData).success(function(response) {
    $scope.data = angular.fromJson(response);
    $scope.complete = false;
    var count=0;
    for(var i = 0; i < $scope.data.length; i++){
        count++;
        $scope.months.push($scope.data[i].month);
        $scope.retail.push($scope.data[i].retail);
        $scope.wholesale.push($scope.data[i].wholesale);
        if(count == $scope.data.length){
            $scope.fetchChart();
            $scope.complete = true;
        }
    }

    $scope.toggleHighCharts = function () {
        this.chartConfig.useHighStocks = !this.chartConfig.useHighStocks
    }

    $scope.$watch("complete",function(){
        alert(JSON.stringify($scope.months)+"---"+JSON.stringify($scope.retail)+"=-=--"+JSON.stringify($scope.wholesale));
    },true);

    $scope.reflow = function () {
        $scope.$broadcast('highchartsng.reflow');
    };
});

$scope.chartTypes = [
{"id": "line", "title": "Line"},
{"id": "spline", "title": "Smooth line"},
{"id": "area", "title": "Area"},
{"id": "areaspline", "title": "Smooth area"},
{"id": "column", "title": "Column"},
{"id": "bar", "title": "Bar"},
{"id": "pie", "title": "Pie"},
{"id": "scatter", "title": "Scatter"}
];

$scope.dashStyles = [
{"id": "Solid", "title": "Solid"},
{"id": "ShortDash", "title": "ShortDash"},
{"id": "ShortDot", "title": "ShortDot"},
{"id": "ShortDashDot", "title": "ShortDashDot"},
{"id": "ShortDashDotDot", "title": "ShortDashDotDot"},
{"id": "Dot", "title": "Dot"},
{"id": "Dash", "title": "Dash"},
{"id": "LongDash", "title": "LongDash"},
{"id": "DashDot", "title": "DashDot"},
{"id": "LongDashDot", "title": "LongDashDot"},
{"id": "LongDashDotDot", "title": "LongDashDotDot"}
];

$scope.chartSeries = [
{"name": "Retail", "data": $scope.retail, type: "column"},
{"name": "Wholesale", "data": $scope.wholesale, type: "column"}
];

In my HTML:

<div>
    <highchart id="chart1"  config="chartConfig"></highchart>
</div>

In the controller:

$scope.data = angular.fromJson(response);

I receive the following data:

[{"wholesale":"1","retail":"0","month":"Jan"},
{"wholesale":"2","retail":"0","month":"May"},
{"wholesale":"0","retail":"1","month":"Jun"},
{"wholesale":"0","retail":"2","month":"Jul"}]

When I use the following code:

$scope.$watch("complete",function(){
    alert(JSON.stringify($scope.months)+"---"+JSON.stringify($scope.retail)+"=-=--"+JSON.stringify($scope.wholesale));
},true);

I get the data as:

["Jan","May","Jun","Jul"]---["0","0","1","2"]=-=--["1","2","0","0"]

In the series:

series: [{  name: 'Retail',
            data: $scope.retail
        },
        {   name: 'Wholesale',
            data: $scope.wholesale
        }
        ],

When I replace data: $scope.retail with

data: [250,500,1500,1800]//$scope.retail
and data: $scope.wholesale with
data: [700,800,200,1300]//$scope.wholesale
, it works. How can I display the chart with dynamic data?

Answer №1

Solution to the Issue:

After successfully resolving the problem independently, I am sharing the solution for my own future reference and to assist anyone facing a similar requirement.

$scope.$watch("comlete",function(){
                        alert(JSON.stringify($scope.months)+"---"+JSON.stringify($scope.retail)+"=-=--"+JSON.stringify($scope.wholesale));
                      },true);

In the provided code snippet, the $scope.retail and $scope.wholesale data are represented as string arrays. The issue arises in the section:

 series: [{
           name: 'Retail',
           data: $scope.retail
           },
           {
           name: 'Wholesale',
           data: $scope.wholesale
           }
           ],

The 'series' component does not accept string data. To resolve this, the strings need to be converted into numbers for the 'series' to accept it. The corrected solution is as follows:

if(angular.isNumber($scope.data[i].retail))
{
 $scope.retail.push($scope.data[i].retail);
}else{
    $scope.retail.push(+$scope.data[i].retail);
    }
if(angular.isNumber($scope.data[i].wholesale))
{
$scope.wholesale.push($scope.data[i].wholesale);
}else{
$scope.wholesale.push(+$scope.data[i].wholesale);
}

Instead of simply using:

$scope.retail.push($scope.data[i].retail);
 $scope.wholesale.push($scope.data[i].wholesale);

These alterations are necessary within the for loop.

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 on implementing a circular progress bar with locomotive scroll functionality

Can anyone help me integrate progress functionality with Locomotive Scroll using JavaScript? Link to CodePen for reference Check out this code snippet from Locomotive Scroll that calculates the percentage of pages scrolled: const scroller = new Locomotiv ...

How can I adjust the font size of material-ui buttons while ensuring that they scale appropriately?

Having trouble adjusting the font sizes on Material-UI's RaisedButton for React and ensuring that the button scales properly along with it. <RaisedButton label={<span className="buttonText">Log in Here</span>} /> CSS: .buttonText ...

The issue with Framer motion's whileInView is that it does not animate the element when it is within the viewport in Next.js

In my current Next.js 14 project with the App Router, I decided to play around with animations using Framer Motion. One specific feature I wanted to implement was animating text elements into view as they enter the viewport. The idea is for the text to gra ...

Jasmine for testing HTTP POST method in a unit test case

I am struggling to write a unit test case for the post method in an Angular service. I keep getting an error saying $http is undefined. Below you can see my code. Can anyone please help me figure out what I am missing? I am adding the module using a separ ...

Implementing a personalized filter onto the footer of an AngularJS UI Grid

After successfully creating a custom filter for my ui-grid that limits decimal numbers to two places and exporting it as a pdf using ui-grid-exporter, I encountered an issue. The filter works fine when exporting the main ui-grid but fails to apply within t ...

Utilize React HOC (Higher Order Component) and Redux to retrieve data and pass it as props

In my quest to develop a Higher Order Component (HOC) that can execute methods to fetch data from the backend and display a loader mask during loading, I encountered a challenge. I aim to have the flexibility of passing different actions for various compon ...

"jQuery's .each() method is only iterating through the last element in

I am encountering an issue with this function not operating correctly... only the last Element shows the box. NOTES: <aside> is set to position: fixed; and I understand that this is not the "correct" use of <article> tags, but it helps me dist ...

DNN Unveils New "Exit Confirmation" Pop-up Feature When Clicking External Links

Greetings fellow beginners! I've been struggling to make some changes on our DNN site (Evoq 8.5) with no success so far. The issue at hand is that we have links throughout our entire website that follow this format: <a href="www.site.com" class="e ...

What is the best way to incorporate multiple pages into a Node JS and Express application?

After completing a tutorial on Node JS for RPI (https://www.youtube.com/watch?v=QdHvS0D1zAI), I encountered an issue when trying to add multiple websites to my web app. While everything works fine locally on localhost:5000/page2, once I make the app public ...

Mapping Dropdown values into another dropdown within AngularJS

I'm facing an issue with my dropdown menu. It has two options: Randomslab and standard style. When I select Randomslab, I want only one value to appear in the next dropdown (300*300). On the other hand, if I choose standard style, then all values sh ...

In the world of Node.js and Java, the concepts of "if"

Here is a code snippet that I am working with: var randFriend = friendList[Math.floor(Math.random() * friendList.length)]; if (randFriend == admin) { //Do something here } else if (randFriend != admin) { client.removeFriend(randFriend); } I am tr ...

Problem with Express.js serving dynamically generated index.html page

Currently, I'm immersing myself in a practice project to grasp the concepts of express and webpack with react and react router. My goal is to make sure all server requests are directed to index.html to avoid encountering "Cannot GET" errors when navig ...

Setting up Jest

I'm currently attempting to integrate the Jest Testing framework into my React Native project. Unfortunately, I am encountering an error message: Failed to retrieve mock metadata: /Users/me/Documents/Development/project/node_modules/global/window.js ...

Creating fluid motion with a bezier curve in ThreeJS

I am looking to animate a bezier curve in ThreeJS with updating start, end, and control points. Eventually, I will have multiple curves animating simultaneously. What is the most efficient approach to achieve this? When running the code snippet below, you ...

Challenges with using async await alongside synchronous functions

I'm currently navigating through a library that utilizes async functions and feeling a bit overwhelmed. I'm attempting to call a function that should return a string, but I'm hitting some roadblocks. As I understand it, the ZeroEx library fu ...

Adding an ellipsis (...) at the end of a specific number of characters within AngularJS

My current project involves extracting educational data from Facebook and displaying it on my webpage. However, I have run into an issue with strings that are too long. I am looking for a solution to truncate the string after a certain number of characters ...

javascript authorization for iframes

I am currently working on a localhost webpage (parent) that includes an iframe displaying content from another url (child; part of a different webapp also on localhost). My goal is to use JavaScript on the parent-page to inspect the contents of the iframe ...

Node.js Sparse Array Memory Usage Explained

I created a program that generates arrays and noticed an interesting behavior: var results = []; var i = 1; while (true) { console.log(i++); results.push([]); } However, when I modify the program to create sparse arrays instead of empty ones, it cra ...

On initial load, React router switch fails to find a match

I am encountering an issue with my switch and react-router. Whenever I open a new tab and navigate to any path, it always redirects me to /login. However, if I remove the bottom switch (the one without a path - the default), everything works as expected. A ...

End your Idp session and log out using passport-saml

Encountering a 400 bad request error when attempting to log out a user from the idp session. Despite successfully logging out the user from the application/passport session, they remain logged in to the idp session. The logout and callback endpoints are c ...