ifeelmyself ifeelmyself - 4 months ago 8
AngularJS Question

How to write with good practice?

I am trying to create chart with chart.js and I would like to get data to chart from backend, but first I need to call function that exists in my controller. I am trying to call this function from 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:

(...)

.controller('DashboardController', function ($scope) {
$scope.getChartLabels = function() {
return ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"];
}

$scope.getChartData = function() {
return [12, 19, 3, 5, 2, 3];
}
}

(...)


How to call angular function getChartLabels() or getChartData() from index.html without bad practices?

Answer

Ideally you should do otherwise and call the javascript methods to draw chart via 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.
    }