Мне нужно создать динамическое количество кольцевых диаграмм с помощью ChartJS на моей странице. У меня это работает, но со статическими данными (2 диаграммы и данные, которые они используют).
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">×</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">×</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>
Сейчас все статично. Мне нужно преобразовать его в динамический. Внутри divChartGroup может быть N графиков шкалы. Для этого я использую AngularJs. Вот код, который я использую для получения данных с помощью 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);
}
Как я могу сгенерировать нужный HTML-код с привязкой событий к кнопкам и динамически создавать диаграммы?



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Это может немного помочь вам в динамическом создании того, что вам нужно.
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>Спасибо. Это помогло.
Как сделать то же самое в Angular?
Параметр значения - это оценка json?