Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-click not working with chart.js

I created a pie chart with chartjs, but when I click on a specific slice, the click event is not taken.

View:

<div ng-controller="ProjectsController">
<a>Projects</a>
<br>
</br>
<canvas id="myPieChart" width="600" height="600" ng-click="chartClick()"></canvas>

Controller:

'use strict';

angular.module('Progs')

.controller('ProjectsController', ['$scope', '$rootScope', '$http', '$window', '$state',
function ($scope, $rootScope, $http, $window, $state) {
  //...
  $scope.chartClick = function (event) {
    console.log('chartClick');
    //console.log("segment: " + $scope.chart.getSegmentsAtEvent(event));
  }
  //...
}

What's wrong with my code?

Please note: I am not using angular-chart.js

like image 349
eeadev Avatar asked Feb 01 '16 11:02

eeadev


2 Answers

I studied your problem and be reading @MohammadMansoor's answer I tried to implement the solution for you.

(function(angular) {
  var app = angular.module("app", []);
  app.controller("ChartCtrl", ['$scope', function($scope) {
    $scope.hello = "Hello, World";
    $scope.canvas = document.getElementById("myPieChart");
    $scope.ctx = $scope.canvas.getContext("2d");
    $scope.data = [{
      value: 300,
      color: "#F7464A",
      highlight: "#FF5A5E",
      label: "Red"
    }, {
      value: 50,
      color: "#46BFBD",
      highlight: "#5AD3D1",
      label: "Green"
    }, {
      value: 100,
      color: "#FDB45C",
      highlight: "#FFC870",
      label: "Yellow"
    }];
    $scope.myPieChart = new Chart($scope.ctx).Pie($scope.data,{});
    $scope.chartClick = function (event) {
        console.log('chartClick');
        console.log($scope.myPieChart.getSegmentsAtEvent(event));
    }
    $scope.canvas.onclick = $scope.chartClick;
  }]);
})(angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.js"></script>

<div ng-app="app" ng-controller="ChartCtrl">
  <h1>{{hello}}</h1>
  <a>Projects</a>
  <br>
  <canvas id="myPieChart" width="600" height="600"></canvas>
</div>

here is the plunk for the same implementation

like image 187
Minato Avatar answered Sep 18 '22 13:09

Minato


Use html onclick feature and access the scope using any id

Example:

<canvas id="myPieChart" width="600" height="600" onclick="angular.element("#myPieChart").scope().chartClick();"></canvas>
like image 34
Mohammed mansoor Avatar answered Sep 17 '22 13:09

Mohammed mansoor