ChartJS: Get value of label when clicked on bar chart

冷暖自知 提交于 2020-05-30 08:04:42

问题


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!


回答1:


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!



来源:https://stackoverflow.com/questions/39768091/chartjs-get-value-of-label-when-clicked-on-bar-chart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!