简体   繁体   中英

ChartJS - Show percentage on hover (AngularJS)

I have simple chartjs in angularjs, and I would show (%) when hovering.

HTML

<div ng-app="chartDemo" ng-controller="MainController as mainCtrl">
      <canvas id="doughnut" class="chart chart-doughnut"
        chart-data="mainCtrl.data" chart-labels="mainCtrl.labels" chart-options="mainCtrl.options">
      </canvas>
</div>

JS

angular.module('chartDemo', ['chart.js'])
    .config(['ChartJsProvider', function (ChartJsProvider) {
    // Configure all charts
    ChartJsProvider.setOptions({
      //animation: false,
      //responsive: false
    });
  }])
    .controller('MainController', MainController);

function MainController($scope, $timeout) {
  var vm = this;
  
  vm.labels = ["Download Sales", "In-Store Sales", "Mail-Order Sales"];
  vm.data = [300, 500, 100];
  vm.options = {
    legend: {
      display: true,
      position: 'bottom'
    },
    cutoutPercentage: 60,
    tooltipEvents: [],
    tooltipCaretSize: 0,
    showTooltips: true,
    onAnimationComplete: function() {
      self.showTooltip(self.segments, true);
    }
  }
  
}

MainController.$inject = ['$scope', '$timeout'];

I've tried look everywhere in their documentation site, but see nothing to do that.

Any sugesstion for me to get that working?

Fiddle

https://jsfiddle.net/bheng/3pw5oLyh/

You can use the label callback in the tooltips section of the options.

  vm.options = {
    legend: {
      display: true,
      position: 'bottom'
    },
    tooltips: {
        callbacks: {
        label: (ttItem,data) => (`${data.labels[ttItem.index]}: ${data.datasets[ttItem.datasetIndex].data[ttItem.index]}%`)
      }
    },
    cutoutPercentage: 60,
    tooltipEvents: [],
    tooltipCaretSize: 0,
    showTooltips: true,
    onAnimationComplete: function() {
      self.showTooltip(self.segments, true);
    }
  }

Updated fiddle example: https://jsfiddle.net/Leelenaleee/9ghu8efs/5/

You can modify data as actual percentages and tooltip value with tooltip callback . In particular label .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM