这是我的 JSON 文件中的 JSON 数据
{"diskspace":100,"diskspace.free":50,"time":8,"time.played":2,"controllers":25,"controllers.used":3, "controllers.new":10, "controllers.broken":12}
我想做的是以饼图的几种形式显示上面的Json数据。例如,一个饼图将显示 diskspace/diskspace.free,这基本上是一个 50%50 的图表。
问题是,当 Json 文件采用所示格式时,我无法获取要显示的数据。但是,如果我将文件中的 json 数据更改为列和行格式,我设法找到一种显示它的方法,但这很不方便,因为我需要为每个图表创建一个单独的 json 文件。
现在它返回的只是一个空白页面,我相信它确实包含一个空图表,因此它不可见。
这是我的 JS
var app = angular.module('charts', []);
app.directive('highchart', function () {
return {
restrict: 'E',
template: '<div></div>',
replace: true,
link: function (scope, element, attrs) {
scope.$watch(function () { return attrs.chart; }, function () {
if (!attrs.chart) return;
var charts = JSON.parse(attrs.chart);
$(element[0]).highcharts(charts);
});
}
};
});
app.controller('Ctrl', function ($scope, $http, $timeout) {
$http.get('bla.json').success(function (key, data) {
// var score = [];
// for (var i = 0; i < data.length; i++) {
// score.push(data[i]);
// }
// var name = [];
// for (var i = 0; i < data.length; i++) {
// name.push(data[i].key);
// }
$scope.renderChart = {
chart: {
type: 'pie'
},
series: [{
data: data
}],
legend: {
enabled: true
}
};
}).error("error message");
$timeout($scope.fetch, 1000);
});
HTML
<!DOCTYPE>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Dashboard Application</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<section ng-app="charts">
<div ng-controller="Ctrl">
<highchart chart='{{renderChart}}'></highchart>
<table>
<tr ng-repeat="record in overSpeedWorstRecords">
<td></td>
<td></td>
</tr>
</table>
</div>
</section>
</body>
</html>
我还创建了一个plunker LINK因此,请随意调整它,非常感谢您的帮助。
最佳答案
你的格式真的不太容易解析。我的意思是,在 keys 中,你有不同的名称,这很难定义解析规则。为什么不使用这样的东西:
{
"diskspace": [
["total", 100],
["free",50]
],
"time": [
["total", 8],
["played", 2]
],
"controllers": [
["total", 25],
["used", 3],
["new", 10],
["broken",12]
]
}
现在您可以创建多个饼图:http://plnkr.co/edit/AqVbfE3mxCf7ahAfKtRG?p=preview
Controller 的简单改进:
var series = [],
iterator = 1;
for (var key in keys) {
series.push({
data: keys[key], // add data from the new format
center: [(25 * iterator) + '%', '50%'] // calculate where center of the pie should be
});
iterator++;
};
$scope.renderChart = {
chart: {
type: 'pie'
},
plotOptions: {
pie: {
size: '25%' // change size of the pies
}
},
series: series,
legend: {
enabled: true
}
};
注意:我不确定这些图表应该如何准确地呈现为饼图(时间 vs time.played?或 time+time.played vs time.played?)。在我看来,对于您的用例来说,可能是更好的选择:http://plnkr.co/edit/Bydq5NG6BkG2LOqhQwzF?p=preview
关于javascript - 从本地 (OBJECT) JSON 文件中的数据创建饼图 Highcharts ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35457390/