0

I am new to AngularJS. I have created a horizontal bar chart by using Chart.js and HTML. Now I would like to add AngularJS so that the chart is dynamically shown on the page. Could some one guide me how to start? Thanks.

HTML:

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.min.js"></script>
<canvas id="myChart"></canvas>

JavaScript:

var config = {
      type: 'horizontalBar',
      data: {
        labels: ["A", "B", "C", "D", "E"],
        datasets: [{
          label: "Dataset 1",
          backgroundColor: "rgba(154,178,96,0.5)",
          hoverBackgroundColor: "rgba(154,178,96,1)",
          data: [10, 15, 5, 81, 55],
        }, {
          label: "Dataset 2",
          backgroundColor: "rgba(197,213,167,0.5)",
          hoverBackgroundColor: "rgba(197,213,167,1)",
          data: [90, 85, 95, 19, 45]
        }]
      },
      options: {
        scales: {
          xAxes: [{
            stacked: true
          }],
          yAxes: [{
            stacked: true
          }]
        }
      }
    };

    var ctx = document.getElementById("myChart").getContext("2d");
    new Chart(ctx, config);
almcd
  • 1,069
  • 2
  • 16
  • 29
Dee
  • 1
  • 1
  • 3

1 Answers1

0

How to Encapsulate jQuery code in a Custom Directive1

Any jQuery code that manipulates the DOM should be encapsulated in a custom directive so that it is executed when the AngularJS framework instantiates the element.

app.directive("myChartJs", function()
     var config = {
         //....
     };
     return {
         link: postLink,
     };
     function postLink(scope,elem,attrs) {
         var ctx = elem[0].getContext("2d");
         new Chart(ctx, config);
     }
});

Usage:

<canvas id="myChart" my-chart-js>
</canvas>

To use jQuery, simply ensure it is loaded before the angular.js file.

For more information, see

georgeawg
  • 48,608
  • 13
  • 72
  • 95