ChartJS:单击条形图时获取标签的值 [英] ChartJS: Get value of label when clicked on bar chart
问题描述
我想在Angular JS中的条形图上单击时获取标签的值。我有html模板:
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>
这是我用于点击事件的JS:
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);
}
};
我想要做的是单击条形图时显示标签的值,更多我特别想获得_model-> label的值。下面是在控制台中打印的内容的图片。
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.
此行:控制台。 log( Point,points [0] .value);
返回未定义。
谢谢!
推荐答案
尝试在 $ scope.onClick
回调中包含第三个变量,单击该变量即可定义一个特定的酒吧。
Try including the third variable in the $scope.onClick
callback, which gets defined when you click a particular bar.
在HTML中:
<canvas id="bar"
... other stuff ...
chart-click="ctrl.onClick">
</canvas>
在控制器中:
ctrl.onClick = function(_points, _event, barClicked) {
if (barClicked) {
var associatedLabel = barClicked._model.datasetLabel;
console.log("Label of the bar you clicked is " + associatedLabel);
}
}
我在每个 year
,最初只使用了两个回调变量,但是所有 _points
给我的都是一年中的所有图表元素我点击了。
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.
我在ChartJS文档中找不到此栏,因此我不确定它是否在所有情况下均适用,但这为我创造了奇迹。干杯!
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!
这篇关于ChartJS:单击条形图时获取标签的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!