我有以下 angularJS 指令
app.directive('answersPlot', function() {
return {
scope: {
chartData: "=chartData",
chartType: "=chartType"
},
template: '<canvas width="100px" height="100px" style="width:100px; !important height:100px; !important"></canvas>',
link: function(scope, element, attrs) {
var canvas = element[0].childNodes[0];
var context = canvas.getContext('2d');
var chart = new Chart(context);
if (scope.chartType == 0) {
chart.Bar(scope.chartData, {});
} else {
chart.Pie(scope.chartData, {});
}
}
}
});
我正在像这样的 ng-repeat DOM block 内实例化它
<div ng-repeat="question in talk.questions track by $index">
<answers-plot chart-data="question.chartData" chart-type="question.chartType"></answers-plot>
</div>
然而,当我检查 DOM 时,我发现了这个
<answers-plot chart-data="question.chartData"
chart-type="question.chartType"
class="ng-isolate-scope">
<canvas width="0" height="0" style="width: 0px; height: 0px;"></canvas>
</answers-plot>
控制台中没有记录任何错误。 chartData
具有以下格式:"{"labels":["A","C","D","B"],"datasets":[{"data":[ 0,2,0,1]}]}"
。
手动更改宽度/高度值(在 CSS 中和作为属性)只会产生更大的空白 Canvas 。
我尝试过两个遇到同样问题的 AngularJS ChartJS 库,我尝试编写自己的指令来验证数据是否确实到达了 ChartJS 库。还是没有坚果。我做错了什么?
最佳答案
前几天我也遇到了同样的问题。
我发现:
<canvas>
的父级是 <answers-plot>
,以及<answers-plot>
的宽度和高度都是0。看来Chartjs
根据<canvas>
的父元素的大小调整其图表的大小这会导致 Canvas 的宽度和高度为 0。
我用了<div>
包裹 <canvas>
在我的指令模板中,并为 <div>
提供了非零大小
或
设置responsive
(在 Chartjs
的选项中)到 false
,问题就解决了。
关于angularjs - 为什么 ChartJS 图表最终的宽度为 0,高度为 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31544126/