单击按钮时添加新的chart.js,但得到“无法读取属性' getContext' of null'

时间:2016-02-19 12:47:24

标签: javascript html angularjs chart.js

我喜欢在点击&#34时添加新图表;添加图表"按钮。该图表目前不包含任何数据,但稍后会添加。无论如何,当我点击"添加图表"我得到" Cannot read property 'getContext' of null"。我认为问题是我的javascript在HTML加载完成之前就已经运行了。但是不知道如何解决它..我已经尝试使用$ jQuery .ready函数,并在canvas标记之后添加脚本..

我的代码:

app.js

'use strict';
require('angular');
require('angular-route');
require('angular-animate');
var chartsCtrl = require('./controllers/chartsCtrl');

var app = angular.module('DashBoard', ['ngRoute', 'ngAnimate'])

//Load controller
app.controller('chartsCtrl', ['$scope', chartsCtrl]);

chartsCtrl.js:

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

    $scope.charts = [];
    var chartId = 0;
    $scope.addChart = function() {
       chartId ++;
       $scope.charts.push({msg: 'Chart added!!', id: chartId});
       new Chart(document.getElementById(chartId).getContext('2d')).Line();
};

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

charts.html:

<div ng-controller='chartsCtrl'>  
    <div class="row">
        <div class="col-md-3" ng-repeat="chart in charts">
            <div class="panel panel-default">
                <div class="panel-body">
                    {{chart.msg}} {{chart.id}} <i class="fa fa-times" ng-click="closeChart($index)"></i>
                    <canvas id={{chart.id}} width="400" height="200"> </canvas>
                </div>
            </div>
        </div> 
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

你试图在视图完成渲染之前获取元素,向控制器注入$timeout并包装DOM操作部分以确保元素已经在文档中,这应该有效: / p>

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);
    }; 
};