0
votes

I am using Chart Js and Angular Chart Directive. I need bar chart dynamically in my ng-repeat directive. https://jtblin.github.io/angular-chart.js/

According to their documentation i have to give two arrays

  $scope.labels = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
  $scope.data = [
    [65, 59, 80, 81, 56, 55, 40]
  ];

I have made two functions in my controller for generating graph label and data array.

 $scope.makeChartLbl=function(data)
    {
      console.log(data);
       var arr=[];
       for(var d in data)
       {
          arr.push(d.name)
       }

       // console.log(arr);
       return arr;
    }

    $scope.makeChartData=function(data)
    {
      console.log(data);
       var arr=[];
       for(var d in data)
       {
          arr.push(d.total_vote)
       }

       // console.log(arr);
       return arr;
    }

My options object in dataset like as

    { 
      "options": [
                {
                    "id": 1,
                    "pool_id": 1,
                    "name": "pool1 option1",
                    "total_vote": 1
                },
                {
                    "id": 2,
                    "pool_id": 1,
                    "name": "pool1 option2",
                    "total_vote": 0
                },
                ...
                ...
            ]
   }

In view with ng-repeat directive

  <canvas id="bar" class="chart chart-bar"
        chart-data="makeChartData(options)" chart-labels="makeChartLbl(options)">
    </canvas>

but it is not generating chart. How can solve this issue?

1

1 Answers

0
votes

There are multiple issues : I am not sure you are reading your Object correctly, check the code for my implementation; The other issue is that Angular trows a $rootScope:infdig error due to how you are creating new arrays inside your functions, I fixed that as well, but you might need to modify it for your particular case.

This is one solution:

var chartData = [];
var chartLabels = [];

$scope.options = options;

$scope.makeChartLbl = function(data) {
chartData.length = 0;
        data.forEach(function(datum) {
        chartData.push(datum.name);
      });
return chartData;
}

$scope.makeChartData = function(data) {
chartLabels.length = 0;
        data.forEach(function(datum) {
        chartLabels.push(datum.total_vote);
      });
return chartLabels;
}

}]);


var options =  [
            {
                "id": 1,
                "pool_id": 1,
                "name": "pool1 option1",
                "total_vote": 1
            },
            {
                "id": 2,
                "pool_id": 1,
                "name": "pool1 option2",
                "total_vote": 0
            }
        ];

Full code in codepen:

Angular Chart.js issue

Result:

enter image description here