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);
2
  • HTML Code:<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.min.js"></script> <canvas id="myChart"></canvas> Commented May 3, 2019 at 18:47
  • Any example which can explain linking directives / templates and controller in Angular js will be highly appreciated. Thanks. Commented May 3, 2019 at 21:13

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.