2015-07-21 38 views
1

我有以下angularJS指令为什么ChartJS图表会以0和0的宽度结束?

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-重复DOM块内像这样

<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中作为属性)只会生成更大的空白画布。

我已经尝试了两个经历同样问题的angularjs chartjs库,使用编写自己的指令来验证数据实际上是到达chartjs库。仍然没有坚果。我究竟做错了什么?

回答

0

<canvas>元素的widthheight属性是无单位的,所以用:

template: '<canvas width="100" height="100" style="width:100px; !important height:100px; !important"></canvas>' 
+2

还没有骰子,同样的问题。 ChartJS会将宽度和高度(在CSS和属性中)都替换为0. – Machinarius

0

我发现类似的行为与Aurelia大街(而不是角) - 它不喜欢撕心裂肺与元素内的图表一个自定义名称,在你的情况下“答案 - 情节”。通过Aurelia,我可以将“无容器”添加到我的自定义元素中,并且工作正常。我不确定使用Angular指令 - 也许在指令选项中替换:true或transclude:true?

3

我前几天遇到同样的问题。
我发现:

<canvas>父是<answers-plot>,并且<answers-plot>的宽度和高度都为0似乎Chartjs根据<canvas>父元素的尺寸引起的宽度大小调整它的图表和画布的高度为0

我用<div>包裹<canvas>在我指导的模板,并给了一个非零大小的<div>

设置responsive(在Chartjs的选项)至false,问题就解决了。

+0

谢谢生活保护程序 – tom10271

相关问题