Populate (Draw) ChartJS Line Chart from database using Web API in AngularJS

Last Reply 29 days ago By dharmendr

Posted 29 days ago

How to get data from database and display it in line chart using chart.js in angularjs using web api?

You are viewing reply posted by: dharmendr 29 days ago.
Posted 29 days ago

Hi skp,

Check this example. Now please take its reference and correct your code.

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular-chart.js/1.0.3/angular-chart.min.js"></script>
    <script type="text/javascript">
        var app = angular.module("MyApp", ["chart.js"]);
        app.controller("MyController", function ($scope, $http) {
            $http.post("http://localhost:9344/LineChart_API/API/GetChartData", {
                headers: { 'Content-Type': 'application/json' }
            }).then(function (response) {
                $scope.months = eval(response.data.d);
                $scope.colors = ['#00FF00'];
                $scope.labels = [];
                var value = [];
                for (var i = 0; i < $scope.months.length; i++) {
                    if ($scope.months[i].Value != 0) {
                        $scope.labels.push($scope.months[i].Name);
                        value.push($scope.months[i].Value);
                    }
                }
                $scope.data = [value];
            });
        });
    </script>
</head>
<body ng-app="MyApp" ng-controller="MyController">
    <canvas id="base" class="chart-line" chart-data="data" chart-labels="labels" width="281%"
        chart-colors="colors" chart-options="options" style="margin-top: 12%"></canvas>
</body>
</html>

WebAPI

public List<ChartData> GetChartData()
{
    // Get data from Database.
    List<ChartData> chartData = new List<ChartData>();
    chartData.Add(new ChartData { Name = "Jan", Value = 1860000 });
    chartData.Add(new ChartData { Name = "Feb", Value = 1850000 });
    chartData.Add(new ChartData { Name = "Mar", Value = 1840000 });
    chartData.Add(new ChartData { Name = "Apr", Value = 1820000 });
    chartData.Add(new ChartData { Name = "May", Value = 1830000 });
    chartData.Add(new ChartData { Name = "Jun", Value = 1800000 });
    chartData.Add(new ChartData { Name = "Jul", Value = 1810000 });
    return chartData;
}

public class ChartData
{
    public string Name { get; set; }
    public int Value { get; set; }
}

Screenshot