Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular chart.js onClick is not working - how to get all elements of a bar when it is clicked on

I am a beginner to Chart.js and I am trying to create click events when a chart is created.

I am trying to access all the elements of a bar when it is clicked on, but right now, the onClick method is not even running properly. The chart is rendering just fine - any html should not be needed as the canvas is created in the code. I would appreciate help in order to solve this problem

controller($state, $scope, $rootScope) {
    $scope.myChart;

....

    $scope.go = function myFunc() {
      document.getElementById("chartContainer").innerHTML = ' ';
      document.getElementById("chartContainer").innerHTML = '<canvas style="margin-top: 10px; padding-top: 20px; height:90% ; background-color: ' + vm.options.backgroundColor + '; " id="myChart" click="onClick"></canvas>';
    var ctx = document.getElementById("myChart").getContext('2d');

       render($scope.myChart, ctx, vm.options.barColor, vm.options.backgroundColor, labelVal, value);
  };
  $scope.onClick = function (evt) {
    console.log("Testing"); 
  };

}
var render = function createChart(myChart, ctx, barColor, backgroundColor, labels, values) {


myChart = new Chart(ctx, {
    type: 'bar',

    data: {
        labels: labels,
        datasets: [{
            backgroundColor: barColor,

            data: values,
                }]

    },
    options: {
        events: ['click'],
        chartArea: {
            backgroundColor: backgroundColor,
        },
        global: {
            responsive: true,
            maintainAspectRatio: false,
        },
        scaleBeginAtZero: true,
        maintainAspectRatio: false,

        scales: {
            xAxes: [{
                ticks: {
                    autoSkip: false,
                }
                }],
            yAxes: [{
                ticks: {
                    beginAtZero: true,
                    min: 0
                }
                    }]
        }
    }
});

}
like image 504
Anonymous Dodo Avatar asked Jun 29 '17 13:06

Anonymous Dodo


1 Answers

TRY adding the following on-click event handler in your chart options ...

options: {
   onClick: function(e) {
      var element = this.getElementAtEvent(e);
      if (element.length) {
         console.log(element[0])
      }
   },
   ...
}

This should work as far as I can tell

like image 130
ɢʀᴜɴᴛ Avatar answered Nov 10 '22 15:11

ɢʀᴜɴᴛ