我正在使用基于Chart.js的AngularJS模块来显示图形。它就像一个魅力,但当我在AngularJS标签集中显示一个图表时,如果图形不是第一个标签,则图形不会呈现。
<tabset>
<tab heading="Tab 1">
<!-- OK -->
<canvas class="chart chart-pie" data="[140, 160]" labels="['d1', 'd2']" legend="true"></canvas>
</tab>
<tab heading="Tab 2">
<!-- Does not render -->
<canvas class="chart chart-pie" data="[140, 160]" labels="['d1', 'd2']" legend="true"></canvas>
</tab>
</tabset>
这是JSFiddle。有没有人设法解决这个问题?
由于
答案 0 :(得分:2)
正如@Martin指出的那样,Chart.js在隐藏的DOM元素中初始化时没有显示图表的问题(即使在显示隐藏元素后其高度和宽度仍保持在0px)。
跟踪此问题here。
如果您被隐藏初始化标签的组件阻止,我会与您分享我的自制解决方案。我创建了一个编译canvas元素的指令。为了能够在需要时刷新元素(例如,当打开选项卡时),我会在控制器中观察属性,我将手动更改选项卡。
这是我的指示:
app.directive('graphCanvasRefresh', ['$compile', function($compile) {
function link(scope, elem, attrs) {
function refreshDOM() {
var markup = '<canvas class="chart chart-pie" id="graph" data="entityGraph.data" labels="entityGraph.labels" legend="true" colours="graphColours" ></canvas>';
var el = angular.element(markup);
compiled = $compile(el);
elem.html('');
elem.append(el);
compiled(scope);
};
// Refresh the DOM when the attribute value is changed
scope.$watch(attrs.graphCanvasRefresh, function(value) {
refreshDOM();
});
// Clean the DOM on destroy
scope.$on('$destroy', function() {
elem.html('');
});
};
return {
link: link
};
}]);
很脏,但这是一个可以使用等待Chart.js更新的工作解决方案。希望它可以帮助别人。
答案 1 :(得分:0)
在@bviale回答中添加了一些功能。
app.directive('graphCanvasRefresh', function ($compile, $timeout) {
return {
scope:{
labels: "=",
data: "=",
type: "=",
refresh: "="
},
link: function (scope, elem, attrs) {
function refreshDOM() {
var markup = '<canvas class="chart chart-' + scope.type + '" id="' + scope.type + scope.$id + '" chart-labels="' + scope.labels + '" ' +
'chart-legend="false" chart-data="' + scope.data +'" ></canvas>';
var newEl = $compile(markup)(scope.$parent.$new());
elem.html(newEl);
scope.refresh = false;
};
// Refresh the DOM when the attribute value is changed
scope.$watch('refresh', function (value) {
$timeout(
refreshDOM(), 100);
});
// Clean the DOM on destroy
scope.$on('$destroy', function () {
elem.html('');
});
}
};
});