[Chartjs]-Add new chart.js when clicking a button, but get 'Cannot read property 'getContext' of null'

2👍

You’re trying to get the element before the view has finished rendering, inject $timeout to your controller and wrap the DOM manipulation part to make sure that the elements are already in the document, this should work:

module.exports = function($scope, $timeout) { 
    var Chart = require('chart.js');

    $scope.charts = [];
    var chartId = 0;

    function initChart( chartIt ) {
        $timeout(function() {
           new Chart(document.getElementById(chartId.toString()).getContext('2d')).Line();
        });
    }

    $scope.addChart = function() {
       chartId ++;
       $scope.charts.push({msg: 'Chart added!!', id: chartId});
       initChart( chartId );
    };

    $scope.closeChart = function(index) {
        $scope.charts.splice(index, 1);
    }; 
};

Leave a comment