2015-07-21 112 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