Search code examples
javascriptangularjshtmlcanvasjs

how to use canvasjs charts in angularjs? multiple charts in angularjs page?


I am using angular.js since 6 months, now I want to use charts in angular.js, I believe CanvasJS is the best chart, its light weight and easy to render, anyone please guide me how to write directives of CanvasJS in angular.js


Solution

  • Muhammad,

    Check this example.

    // data related to AngularJS
    var m = {
      "India": "2",
      "Australia": "3"
    };
    
    function MyCtrl($scope) {
      $scope.items = m;
    }
    
    // data related to CanvasJS Charts
    window.onload = function() {
    
      var dps = [{
        x: 1,
        y: 10
      }]; //dataPoints. 
    
      var chart = new CanvasJS.Chart("chartContainer-Australia", {
        title: {
          text: "Live Data"
        },
        axisX: {
          title: "Axis X Title"
        },
        axisY: {
          title: "Units"
        },
        data: [{
          type: "line",
          dataPoints: dps
        }]
      });
    
      var chart2 = new CanvasJS.Chart("chartContainer-India", {
        title: {
          text: "Live Data"
        },
        axisX: {
          title: "Axis X Title"
        },
        axisY: {
          title: "Units"
        },
        data: [{
          type: "line",
          dataPoints: dps
        }]
      });
    
      chart.render();
      chart2.render();
      var xVal = dps.length - 1;
      var yVal = 15;
      var updateInterval = 1000;
    
      var updateChart = function() {
        yVal = yVal + Math.round(5 + Math.random() * (-5 - 5));
        dps.push({
          x: xVal,
          y: yVal
        });
        xVal--;
        chart.render();
        chart2.render();
    
      };
      setInterval(function() {
        updateChart()
      }, updateInterval);
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
    
    <h3>Match Summary:</h3>
    <div ng-app ng-controller="MyCtrl">
      <div ng-repeat="(country,goals) in items">
        <div id="chartContainer-{{country}}" style="height: 200px; width: 100%;"></div>
        <h2>{{country}}: {{goals}} </h2>
      </div>
    </div>