我想使用Chart.js在我现有的角度应用上创建一个类似仪表板的功能。所以,我为仪表板创建了一个视图。
<md-content layout-padding layout-fill flex class="animated fadeIn">
<div layout-padding>
<md-card-title>
<md-card-title-text>
<span class="md-headline">Dashboard</span>
</md-card-title-text>
</md-card-title>
</div>
<md-divider></md-divider>
<div>
<md-grid-list md-cols-gt-md="12" md-cols-sm="3" md-cols-md="8"
md-row-height-gt-md="1:1" md-row-height="4:3"
md-gutter-gt-md="8px" md-gutter-gt-sm="4px" md-gutter="2px">
<md-grid-tile md-colspan-gt-sm="3" md-rowspan-gt-sm="3">
<pie-chart header="'Auths'" auth-counts="ctrl.authCounts" flex-gt-sm></pie-chart>
</md-grid-tile>
</md-grid-list>
</div>
</md-content>
仪表板控制器从路径(ui.router
)加载。此刻控制器是空的。
//router
.state('home.dashboard', {
url: '/dashboard',
controller: 'DashboardController as ctrl',
templateUrl: baseUrl + 'Scripts/src/views/dashboard/dashboard.home.html'
})
function DashboardController() {
var ctrl = this;
ctrl.$onInit = function () {
console.log('testing');
ctrl.authCounts = [800, 200];
}
}
然后,组件pie-chart
如下所示。
(function () {
'use strict';
angular.module('chart')
.component('pieChart', {
controller: PieChartComponentController,
templateUrl: 'Scripts/src/views/dashboard/pie.chart.template.html',
bindings: {
header: '<',
authCounts: '<'
}
});
PieChartComponentController.$inject = ['$timeout'];
function PieChartComponentController($timeout) {
var $ctrl = this;
$ctrl.$onInit = function () {
var myPieChart;
var data;
}
$ctrl.isArrayEmpty = function (authCount) {
if (!authCount) return true;
return authCount.length === 0;
}
$ctrl.createChart = function () {
var pieData = {
labels: ["Purple","Green","Orange","Yellow"],
datasets: [
{
data: [20, 40, 10, 30],
backgroundColor: ["#878BB6","#4ACAB4","#FF8153","#FFEA88"]
}
]
};
var ctx = document.getElementById("myPieChart").getContext("2d");
var myPieChart = new Chart(ctx, {
type: 'pie',
data: pieData
});
} // end createChart()
}
})();
pie-chart
模板如下所示。
<div layout-align="start center" ng-if="$ctrl.isArrayEmpty($ctrl.authCounts)">
Not enough information available to create the chart.
</div>
<canvas id="myPieChart" width="250" height="250" ng-init="$ctrl.createChart()" ng-if="$ctrl.isArrayEmpty($ctrl.authCounts)" flex-gt-sm></canvas>
</md-card-content>
看起来一切都很好,但画布的高度和宽度为0,并且不会渲染图表。
但是,如果我删除pie-chart
组件,并将<canvas>
元素放在仪表板模板外部并将数据放在仪表板中,则会呈现图表。但这不是我想做的事情。我需要为每种类型都有组件。那么,我做错了什么导致了这种行为呢?
我也尝试angular-chart.js
表现出同样的行为。如果我将<canvas>
元素放在仪表板模板中,它会显示图表,但不会显示pie-chart
元素内部。我需要帮助排除故障。我肯定在这里遗漏了一些东西,但无法弄清楚是什么。画布是在提供数据之前渲染的,还是有些东西在我忽略(或者没有注意到)?