简体   繁体   English

为什么chart.js无法与angular JS一起使用

[英]Why is chart.js not working with angular JS

I am trying to create a chart component in AngularJS (v1.5.8) but for some odd reason chart.js is not getting initialized. 我正在尝试在AngularJS(v1.5.8)中创建一个图表组件,但由于某些奇怪的原因,未初始化chart.js。 http://codepen.io/flyinggambit/pen/eBYezK 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. 但是,同样的代码在vanilla JS中也有效。 http://codepen.io/flyinggambit/pen/MbWOmG http://codepen.io/flyinggambit/pen/MbWOmG

What is the reason for this ? 这是什么原因呢? How can I fix this ? 我怎样才能解决这个问题 ?

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可快速解决您的问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM