为什么chart.js不能使用angular JS

时间:2016-11-04 11:29:44

标签: angularjs chart.js

我正在尝试在AngularJS(v1.5.8)中创建一个图表组件,但由于一些奇怪的原因,chart.js没有被初始化。 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>

然而,同样的代码在vanilla JS中运行。 http://codepen.io/flyinggambit/pen/MbWOmG

这是什么原因?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:5)

您不能将画布作为根元素,然后尝试以您的方式访问它。

将其包裹在另一个div中以快速解决您的问题:

"<div><canvas width='200' height='200' class='{{$ctrl.class}}'></canvas></div>"