I am using angular-chart.js to draw some graphs. And I am using array values to set the values for $scope.labels
and $scope.data
from database. I want to make the $scope.labels
and $scope.data
empty after each call of the function. please find the below code
angular.module("app", ["chart.js"])
.controller("LineCtrl", function ($scope) {
$scope.labels = [];
$scope.data = [[]];
$scope.graphFunc = function(array) {
for(var i =0; i < array.length; i++)
{
$scope.labels.push(array[i].name);
$scope.data[0].push(array[i].age)
}
$scope.onClick = function (points, evt) {
console.log(points, evt);
};
$scope.datasetOverride = [{ yAxisID: 'y-axis-1' }, { yAxisID: 'y-axis-2' }];
$scope.options = {
scales: {
yAxes: [
{
id: 'y-axis-1',
type: 'linear',
display: true,
position: 'left'
},
{
id: 'y-axis-2',
type: 'linear',
display: true,
position: 'right'
}
]
}
};
};
$scope.labels = [];
$scope.data = [[]];
});
But then the graph is not appearing. Please note that my array is a dynamic and array format is as follows
var arrayVal = [{name:A,age:10},{name:B,age:30}];
UPDATED HTML
<canvas id="line" class="chart chart-line" chart-data="data"
chart-labels="labels" chart-series="series" chart-options="options"
chart-dataset-override="datasetOverride" chart-click="onClick">
</canvas>
I could find the issue which is rather than declaring $scope.labels and $scope.data inside controller, by declaring these two global variables inside chartFunc() this issue can be overcome. Therefore you don't have to reinitialize the two variables at the end of the chartFunc().
angular.module("app", ["chart.js"])
.controller("LineCtrl", function ($scope) {
$scope.graphFunc = function(array) {
$scope.labels = [];
$scope.data = [[]];
for(var i =0; i < array.length; i++)
{
$scope.labels.push(array[i].name);
$scope.data[0].push(array[i].age)
}
$scope.onClick = function (points, evt) {
console.log(points, evt);
};
$scope.datasetOverride = [{ yAxisID: 'y-axis-1' }, { yAxisID: 'y-axis-2' }];
$scope.options = {
scales: {
yAxes: [
{
id: 'y-axis-1',
type: 'linear',
display: true,
position: 'left'
},
{
id: 'y-axis-2',
type: 'linear',
display: true,
position: 'right'
}
]
}
};
};
});
What happens is each time the user wants to see a graph the two variables are reinitialized inside the chartFunc and previous array values are removed autuomatically