Reputation: 35
I'm using the Google Chart Tools Directive Module to draw a line/area chart in my Angularjs application, from rdf data retrieved via sparql queries and available, within the app, in json-like format.
In the main controller I declared my drawing function like this:
$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;
}
}]);
And in my HTML I got my chart div:
<div google-chart chart="createChart()" class="mychartClass"></div>
Now the problem with this solution is that the chart gets blank drawn first and - if query doesn't take much time - filled later.
How to wait for data to be retrieved from queries before drawing the chart?
I've tried setting a timeout but this is not the best way to go.
Upvotes: 0
Views: 268
Reputation: 48968
It is better to have the chart directive follow a scope variable:
̶<̶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>
Using a function causes the AngularJS framework to invoke the function every digest cycle. This leads to doing alot of unnecessary computation.
Instead do the computation after the data arrives from the server.
$http.get(url).then(function(response) {
$scope.entities = response.data;
$scope.myChart = $scope.createChart();
});
This way the chart is only computed once when the data arrives from the server.
Upvotes: 0