1

I am trying to create a chart component in AngularJS (v1.5.8) but for some odd reason chart.js is not getting initialized. http://codepen.io/flyinggambit/pen/eBYezK

angular.module("dashboard", [])
  .component("exceptionChart", {
    template: "<canvas width='200' height='200' class='{{$ctrl.class}}'></canvas>",
    bindings: {
      class: '@'
    },
    controller: function($element) {
      this.$postLink = function() {
        
        // code for chart
        var ctx = $element.find('canvas')[0];
        var myChart = new Chart(ctx, {
          type: 'bar',
          data: {
            labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
            datasets: [{
              label: '# of Votes',
              data: [12, 19, 3, 5, 2, 3],
              backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
              ],
              borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
              ],
              borderWidth: 1
            }]
          },
          options: {
            scales: {
              yAxes: [{
                ticks: {
                  beginAtZero: true
                }
              }]
            }
          }
        });
        
        
        
      }
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.bundle.min.js"></script>
<div ng-app="dashboard">
  <exception-chart class=""></exception-chart>
</div>


<canvas id="myChart" width="200" height="200"></canvas>

However the code for the same works in vanilla JS. http://codepen.io/flyinggambit/pen/MbWOmG

What is the reason for this ? How can I fix this ?

1

1 Answer 1

6

You can't have the canvas as the root element and then try to access it in the way you're doing it.

Wrap it in another div to quickly solve your problem:

"<div><canvas width='200' height='200' class='{{$ctrl.class}}'></canvas></div>"
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Oliver, it works though I still don't understand why canvas cannot be the root element.
On second thought, I really think it should work. It doesn't seem to be a problem with access.

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.