[Chartjs]-Dynamically create Angular-Chart with data binding

1👍

You are just updating the data but the chart has been already rendered on your view.So you need to draw it again with updated data. You can make a function to draw chart like this

function drawChart(element,dataset){
  var myChart = new Chart(element,{type:'bar',data:{labels:$scope.labels,datasets :dataset}})
}

and call it when your dataset get chanegd

0👍

One option is to rebuild the chart when the data changes by using the $watch option of angular.

Close to the above example would be

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <title>Chart.js demo</title>
    <script src='Chart.js'></script>
    <script src='angular.js'></script>
    <script src='angular-chart.js'></script>
</head>

<body ng-app="app" ng-controller="Ctrl">
    <textarea ng-model="chart"></textarea>
    <button ng-click="updateConfig();">Update</button>
    <canvas id="myChart"></canvas>
    <script type="text/javascript">

    getSample = function(n) {
        var res = [];
        for (var i = 0; i < n; i++) {
            res.push(Math.round(Math.random() * 100));
        }
        return res;
    }

    var app = angular.module('app', ["chart.js"]);
    app.controller("Ctrl", function Ctrl($scope, $interval) {

        $scope.chart = '{"type": "line"}';
        $scope.labels = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
        $scope.data = getSample(7);

        $scope.updateConfig = function(testFunction) {
            var ctx = document.getElementById("myChart");
            var config = JSON.parse($scope.chart);
            config["data"] = {
                labels: $scope.labels, //should be a reference
                datasets: [{
                    data: $scope.data //should be a reference 
                }]
            }
            var myChart = new Chart(ctx, config);
        };

        $scope.$watch('data', function(){
            var ctx = document.getElementById("myChart");
            var config = JSON.parse($scope.chart);
            config["data"] = {
                labels: $scope.labels, //should be a reference
                datasets: [{
                    data: $scope.data //should be a reference 
                }]
            }
            var myChart = new Chart(ctx, config);
        }, false);

        $interval(function() {
            $scope.data = getSample(7);
            console.log("Changed data to " + $scope.data);
        }, 3000);
    });
    </script>
</body>

</html>

Leave a comment