如何用良好的做法写作?

时间:2016-07-19 14:04:42

标签: javascript angularjs chart.js

我正在尝试使用chart.js创建图表,我想从后端获取数据到图表,但首先我需要调用控制器中存在的函数。我试图从index.html调用此函数。

INDEX:

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('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调用角度函数getChartLabels()或getChartData()?

1 个答案:

答案 0 :(得分:2)

理想情况下,你应该这样做,并调用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.
    }
相关问题