我正在尝试使用 Chart.js 创建图表,我想从后端获取数据到图表,但首先我需要调用 Controller 中存在的函数。我试图从index.html 调用这个函数。
索引:
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: $scope.getChartLabels(),
datasets: [{
label: '# of Votes',
data: $scope.getChartData(),
backgroundColor: [
'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(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: {
responsive: true,
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
Controller :
(...)
.controller('DashboardController', function ($scope) {
$scope.getChartLabels = function() {
return ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"];
}
$scope.getChartData = function() {
return [12, 19, 3, 5, 2, 3];
}
}
(...)
如何从 index.html 调用 Angular 函数 getChartLabels() 或 getChartData() 而没有不良做法?
最佳答案
理想情况下,您应该这样做并调用 javascript 方法通过 angularJs 绘制图表
.controller('DashboardController', function ($scope) {
$scope.getChartLabels = function() {
return ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"];
}
$scope.getChartData = function() {
return [12, 19, 3, 5, 2, 3];
}
drawCharts($scope.getChartLabels,$scope.getChartData);
}
function drawCharts(d1,d2){
// draw charts here.
}
关于javascript - 如何通过良好的练习来写作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38460827/