首页 > 解决方案 > Creating charts dynamically using ChartJS and AngularJS

问题描述

I need to create dynamic number of doughnut charts using ChartJS on my page. I have got this working but with static data(2 charts and the data used by them).

The markup is:

<div class="row" id="divChartGroup">
        <div class="col-md-3 col-lg-3">
            <div class="panel panel-default">
                <div class="panel-body">
                    <button type="button" class="close" data-target="#copyright-wrap" data-dismiss="alert" ng-click="ConfirmRemove('Guage1')"> <span aria-hidden="true">&times;</span><span class="sr-only" style="color:#000 !important">Close</span> </button>
                    <h4>Gauge1</h4>
                    <canvas id="CanvasGauge1"></canvas>
                </div>
            </div>
        </div>
        <div class="col-md-3 col-lg-3">
            <div class="panel panel-default">
                <div class="panel-body">
                    <button type="button" class="close" data-target="#copyright-wrap" data-dismiss="alert" ng-click="ConfirmRemove('Guage2')"> <span aria-hidden="true">&times;</span><span class="sr-only" style="color:#000 !important">Close</span> </button>
                    <h4>Gauge2</h4>
                    <canvas id="CanvasGauge2"></canvas>
                </div>
            </div>
        </div>
        <!-- Can be many more gauge charts here -->
</div>

Right now it is all static. I need to convert it into dynamic. There can be N number of gauge charts inside "divChartGroup". I am using AngularJs for this. Here is the code I use to get the data using AngularJS:

APIService.GetChartData()
        .then(function (response) {
         var data = response.data.result;
         //Gets data in the format provided elow
        //Need to write logic to generate charts dynamically here.       
    }

JSON response(data) is like:

"result": [
        {
            "chartName": "Gauge1",
            "score": 87
        },
        {
            "chartName": "Gauge2",
            "score": 87
        },
        {
            "chartName": "Gauge3",
            "score": 89
        },
        {
            "chartName": "Gauge4",
            "score": 88
        },
        .
        .
        .
        ]

Code to create chart:

function DrawGauge(element, value) {
            var _config = {
                type: 'doughnut',
                data: {
                    labels: [
                        "",
                        ""
                    ],
                    datasets: [{
                        data: [value, 100 - value],
                        backgroundColor: [
                            '#3d9447',
                            '#a7adba'
                        ],
                        hoverBackgroundColor: [
                            '#3d9447',
                            '#a7adba'
                        ]
                    }]
                },
                options: {
                    cutoutPercentage: 80,
                    legend: {
                        display: false
                    },
                    tooltips: {
                        enabled: true
                    },
                    elements: {
                        center: {
                            text: value.toFixed(2),
                            color: '#000000',
                            fontStyle: 'Arial',
                            sidePadding: 20,
                            fontSize: 50,
                            textAlign: 'center'
                        }
                    }
                }
            };

            new Chart(element, _config);
        }

How can I generate the desired HTML with events bind to the buttons and create charts dynamically?

标签: javascriptangularjschart.js

解决方案


这可以帮助您了解如何动态创建所需的内容。

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http, $timeout) {

    $scope.jsonResult = 
    [
        {
            "chartName": "Gauge1",
            "score": 87
        },
        {
            "chartName": "Gauge2",
            "score": 87
        },
        {
            "chartName": "Gauge3",
            "score": 89
        },
        {
            "chartName": "Gauge4",
            "score": 88
        }
    ];

    $scope.initChart = function(idElement) {
        $scope.jsonResult[idElement].id = idElement;
        $timeout(function () {
            for (var i = 0; i < $scope.jsonResult.length; i++) {
                $scope.loadChart($scope.jsonResult[i]);
            }                
        });
    }    

    /*$scope.serviceChart = function() {
        $http.get('data.json').then(function(res) {
            $scope.charts = res.data;
        });
    }*/

    $scope.loadChart = function(idElement) {
        var value = idElement.score;
        var element = $("#myChart"+idElement.id);
        DrawGauge(element, value);
    }

    function DrawGauge(element, value) {
        var _config = {
            type: 'doughnut',
            data: {
                labels: [
                    "",
                    ""
                ],
                datasets: [{
                    data: [value, 100 - value],
                    backgroundColor: [
                        '#3d9447',
                        '#a7adba'
                    ],
                    hoverBackgroundColor: [
                        '#3d9447',
                        '#a7adba'
                    ]
                }]
            },
            options: {
                cutoutPercentage: 80,
                legend: {
                    display: false
                },
                tooltips: {
                    enabled: true
                },
                elements: {
                    center: {
                        text: value.toFixed(2),
                        color: '#000000',
                        fontStyle: 'Arial',
                        sidePadding: 20,
                        fontSize: 50,
                        textAlign: 'center'
                    }
                }
            }
        };

        new Chart(element, _config);
    }

    //$scope.serviceChart();
});
<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8" />
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js"></script>
        
        
    </head>

    <body ng-app="myApp" ng-controller="myCtrl">
        <div ng-repeat="chart in jsonResult track by $index" ng-init="initChart($index)" style="width: 150px; height: 150px;">
            <canvas id="myChart{{ $index }}"></canvas>
        </div>
        <script src="script.js"></script>
    </body>

</html>


推荐阅读