Search code examples
javascripthtmlcanvasjs

AngularJS and CanvasJS Bar Chart Index Labels - how to show them?


I have a basic CanvasJS Chart inside and AngularJS controller that shows data from the $scope of that controller. I don't really know if this information is relevant, but maybe it will help you understand better the context of the creation of the bar chart. Anyways, I want to add Index Labels to each bar, to show the value of each data point above each bar. I looked over the CanvasJS documentation and tried placing Index Label: "{y}" both inside the dataset object and inside the data array but nothing seems to work. The chart loads, but the Index Labels are not visible at all. Here's my chart snippet below.

ageChart = new Chart(document.getElementById("ageChart").getContext("2d")).Bar({
	   labels: ['Critical', 'Major', 'Minor'],
	   datasets: [{
                       fillColor: "rgba(151,187,205,0.5)",
                       strokeColor: "rgba(151,187,205,0.8)",
                       highlightFill: "rgba(151,187,205,0.75)",
                       highlightStroke: "rgba(151,187,205,1)",
                       data: [$scope.employeeData.data1, $scope.employeeData.data2, $scope.employeeData.data3]
				}]
				  }, {showScale: false, responsive: true, barValueSpacing: 25});

Thanks in advance!


Solution

  • Here is a snipped for showing CanvasJS Bar Chart Index Labels using AngularJS.

    var myapp = angular.module("myapp", []);
    
    myapp.controller("MyCtrl", ["$scope",function($scope){
      $scope.data = [{
                      x: 1,
                      y: 10,
                      indexLabel:"{y}"
                    },
                    {
                      x: 2,
                      y: 20,
                      indexLabel:"{y}"
                    },
                    {
                      x: 3,
                      y: 30,
                      indexLabel:"{y}"
                    },
                    {
                      x: 4,
                      y: 20,
                      indexLabel:"{y}"
                    },
                    {
                      x: 5,
                      y: 10,
                      indexLabel:"{y}"
                    }];
      var chart = new CanvasJS.Chart("chartContainer", {
        data: [{
          type: "bar",
          dataPoints: $scope.data
        }]
      });
      chart.render();
    }]);
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
    
    <div ng-app="myapp" ng-controller="MyCtrl">
      <div id="chartContainer" style="height: 320px; width: 100%;"></div>
    </div>

    Hope this will help you out.