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!
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With