[英]Angularjs Google Chart - How to wait for data before draw a chart
我正在使用Google 圖表工具指令模塊在我的 Angularjs 應用程序中繪制折線圖/面積圖,該數據來自通過 sparql 查詢檢索到的 rdf 數據,並且在應用程序中以類似 json 的格式提供。
在主要的 controller 我這樣聲明我的繪圖 function :
$scope.createChart = function () {
var json1 = $scope.entities // here I have my data
var rows = []
// populate array with data:
for (var key in json1) {
if (json1[key]['qb:dataset'] == $scope.dsUri) {
var date = new Date(json1[key]['sdmx-dimension:refTime']);
var deads = json1[key]['dpc:deads'];
var newpos = json1[key]['dpc:newPositive'];
var intcare = json1[key]['dpc:intensiveCare'];
rows.push({ c: [ { v:date }, { v:deads }, { v:newpos }, { v:intcare} ] });
}
}
// sort rows by dates
rows.sort(function (rowA, rowB) {
return rowA.c[0].v.getTime() - rowB.c[0].v.getTime();
});
// define chart object
$scope.myChartObject = {
"type": "LineChart",
"data": {
"cols": [
{
"id": "date",
"label": "Date",
"type": "date"
},
{
"id": "deaths",
"label": "Deaths",
"type": "number"
},
{
"id": "newpos",
"label": "New Positive",
"type": "number"
},
{
"id": "intCare",
"label": "Intensive Care",
"type": "number"
}
]
},
"options": {
"title": "Observations",
"height": 400,
"legend": { position: 'bottom' },
"width": 'auto'
}
}
// add rows to data
$scope.myChartObject.data.rows = rows;
return $scope.myChartObject;
}
}]);
在我的 HTML 中,我得到了圖表 div:
<div google-chart chart="createChart()" class="mychartClass"></div>
現在這個解決方案的問題是圖表首先繪制為空白,並且 - 如果查詢不需要太多時間 - 稍后填充。
如何在繪制圖表之前等待從查詢中檢索數據?
我試過設置超時,但這不是 go 的最佳方法。
最好讓圖表指令遵循 scope 變量:
̶<̶d̶i̶v̶ ̶g̶o̶o̶g̶l̶e̶-̶c̶h̶a̶r̶t̶ ̶c̶h̶a̶r̶t̶=̶"̶c̶r̶e̶a̶t̶e̶C̶h̶a̶r̶t̶(̶)̶"̶ ̶c̶l̶a̶s̶s̶=̶"̶m̶y̶c̶h̶a̶r̶t̶C̶l̶a̶s̶s̶"̶>̶<̶/̶d̶i̶v̶>̶
<div google-chart chart="myChart" class="mychartClass"></div>
使用 function 會導致 AngularJS 框架在每個摘要周期調用 function。 這會導致做很多不必要的計算。
而是在數據從服務器到達后進行計算。
$http.get(url).then(function(response) {
$scope.entities = response.data;
$scope.myChart = $scope.createChart();
});
這樣,圖表僅在數據從服務器到達時計算一次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.