Reputation: 811
I want to get the value of the label when clicked on a bar chart in Angular JS. I have the html template:
<canvas id="bar" class="chart chart-bar" chart-data="data"
chart-labels="labels" chart-legend="true" height="350"
chart-series="series" chart-click="onClick">
</canvas>
here is my JS for the click event:
$scope.onClick = function (points, evt) {
console.log("Chart clicked", points, evt);
console.log(points);
if(points.length > 0){
console.log("Bar chart clicked");
console.log("Point", points[0].value);
}
};
What I want to do is to display the value of the label when clicked on a bar chart, more specifically I want to get the value of _model -> label. Below is a picture of what gets printed in the console.
This line: console.log("Point", points[0].value);
returns undefined.
Thanks in advance!
Upvotes: 4
Views: 9214
Reputation: 11
$scope.onClick = function (points, e, instance) {
$scope.chart = instance._chart;
$scope.activeElement = $scope.chart.getElementAtEvent(e);
console.log(points[0]._chart.data.datasets[$scope.activeElement[0]._datasetIndex].data[$scope.activeElement[0]._index] );
};
Upvotes: 0
Reputation: 1191
Try including the third variable in the $scope.onClick
callback, which gets defined when you click a particular bar.
In the HTML:
<canvas id="bar"
... other stuff ...
chart-click="ctrl.onClick">
</canvas>
In the controller:
ctrl.onClick = function(_points, _event, barClicked) {
if (barClicked) {
var associatedLabel = barClicked._model.datasetLabel;
console.log("Label of the bar you clicked is " + associatedLabel);
}
}
I was rendering multiple bars per year
along the X-axis and originally used just the two callback variables, but all _points
was giving me was all the chart elements within the year I clicked. The above gave me the exact bar I clicked.
I couldn't find this in the ChartJS docs, so I'm not sure if it is applicable in all cases, but it worked wonders for me. Cheers!
Upvotes: 2