2017-09-16 118 views
-1

我想要在chartjs圖表中格式化數字。我爲我的控制檯上得到這個錯誤,而且數字是不可見的圖表Uncaught TypeError:無法讀取未定義的屬性「格式」

Uncaught TypeError: Cannot read property 'format' of undefined

您可以參考小提琴here上。在小提琴

for (var i = 0; i < firstDataSet.data.length; i++) { 
          var firstModel = firstDataSet._meta[Object.keys(firstDataSet._meta)[0]].data[i]._model; 
          var secondModel = secondDataSet._meta[Object.keys(secondDataSet._meta)[0]].data[i]._model; 
          var thirdModel = thirdDataSet._meta[Object.keys(thirdDataSet._meta)[0]].data[i]._model; 
          var fourthModel = fourthDataSet._meta[Object.keys(fourthDataSet._meta)[0]].data[i]._model; 
          var total = firstDataSet.data[i] + secondDataSet.data[i]; 
          var total1 = thirdDataSet.data[i] + fourthDataSet.data[i]; 
    // Line below is causing the error 


ctx.fillText(formatter.format(Number(firstDataSet.data[i])) + " ", firstModel.x, firstModel.y + 20); 

          ctx.fillText((firstDataSet.data[i]) , firstModel.x, firstModel.y + 20); 
          ctx.fillText((secondDataSet.data[i]) , secondModel.x, secondModel.y + 20); 
          ctx.fillText(total , secondModel.x, secondModel.y - 20); 
          ctx.fillText((thirdDataSet.data[i]) , thirdModel.x, thirdModel.y + 20); 
          ctx.fillText((fourthDataSet.data[i]) , fourthModel.x, fourthModel.y + 20); 
          ctx.fillText(total1 , fourthModel.x, fourthModel.y - 20); 
          /*if (firstDataSet.data[i] >= secondDataSet.data[i]) { 
           ctx.fillText((firstDataSet.data[i] * 100/total).toFixed(2) + '%', firstModel.x, firstModel.y + 30); 
          } else { 
           ctx.fillText((secondDataSet.data[i] * 100/total).toFixed(2) + '%', secondModel.x, secondModel.y + 30); 
          } 
          */ 
         } 

var formatter = new Intl.NumberFormat('en-US', { 
    style: 'currency', 
    currency: 'USD', 
    minimumFractionDigits: 2, 
    // the default value for minimumFractionDigits depends on the currency 
    // and is usually already 2 
}); 
+0

聲明''之前= window.myBar新的圖表(CTX formatter' ...'像這樣:[小提琴](https://jsfiddle.net/6j3L6p8s/) – DavidDomain

+0

哦,太好了..這如果你可以添加它作爲答案,我可以接受它 – Prady

回答

1

你必須調用new Chart構造函數之前聲明的formatter 74號線,否則會被undefinedoptions你逝去爲new Chart第二個參數內。

var formatter = new Intl.NumberFormat('en-US', { 
    style: 'currency', 
    currency: 'USD', 
    minimumFractionDigits: 2, 
    // the default value for minimumFractionDigits depends on the currency 
    // and is usually already 2 
}); 

window.myBar = new Chart(ctx, { 
    type: 'bar', 
    data: data, 
    options: options 
}); 
相關問題