添加新图表.js单击按钮时,但得到“无法读取空的属性'getContext'”
Add new chart.js when clicking a button, but get 'Cannot read property 'getContext' of null'
我喜欢在单击"添加图表"按钮时添加新图表。该图表目前不包含任何数据,但稍后将添加。无论如何,当我单击"添加图表"时,我得到" Cannot read property 'getContext' of null
"。我认为问题是我的javascript在HTML完成加载之前正在运行。但不知道如何解决它。 我尝试使用$jQuery.ready函数,并在画布标签之后添加脚本。
我的代码:
应用.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]);
图表按.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);
};
};
图表.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>
您尝试在视图完成渲染之前获取元素,将$timeout
注入控制器并包装 DOM 操作部分以确保元素已经在文档中,这应该有效:
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);
};
};
相关文章:
- TypeError:无法读取属性'推'未定义的JavaScript
- 同样,同样的错误'ahorcado.js:26未捕获类型错误:无法读取属性'beginPath'
- 未捕获的类型错误:无法读取属性'删除'的未定义
- AngularJS指令出错-无法读取属性'编译'的未定义
- 未捕获的类型错误:无法读取属性'name'即使它存在,也无法定义
- 看到“;未捕获的类型错误:无法读取属性'weight'未定义的“;尽管按照字面上的指示
- 无法读取属性'材料'未定义的Three.js
- 得到"TypeError:无法读取属性'filename'未定义的“;调用“npm start
- Soundcloud api"未捕获的类型错误:无法读取属性'uri'“未定义”;
- 未捕获的类型错误:无法读取属性'addEventListener'的null chrome扩展名
- Soundcloud Javascript SDK 3.0-回调无法读取属性'connectCallback
- 未捕获的类型错误:无法读取属性'状态'在react中为null
- JavaScript承诺-无法读取属性'那么'的未定义
- Javascript Float32数组抛出无法读取属性'0'即使数组定义良好,也为null
- 未捕获的类型错误:无法读取属性'中止'的未定义
- 角度推入数组给出:TypeError:无法读取属性'推'的未定义
- http/rxjs catch回调中的Angular 2重定向导致TypeError:无法读取属性'订阅'
- Javascript未捕获类型错误:无法读取属性'0'的未定义
- jQuery控制台错误:无法读取属性'top'的未定义
- TypeError:无法读取属性'findAll'的未定义