AngularJS 选项卡集中的 Chart.js 不呈现

我正在使用基于 Chart.js 的 AngularJS 模块来显示图形.它就像一个魅力,但是当我在 AngularJS 选项卡集中显示图表时,如果它不是第一个选项卡,则该图表不会呈现.

I am using a AngularJS module based on Chart.js to display graph. It works like a charm, but when I display a chart in a AngularJS tabset, the graph does not render if it is not the first tab.

  <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.有人设法解决这个问题吗?

This is the JSFiddle. Does anyone manage to fix this ?

谢谢

推荐答案

正如@Martin 指出的那样,在隐藏的 DOM 元素中初始化时 Chart.js 不显示图表的问题(其高度和宽度保持在0px 即使在显示隐藏元素之后).

As @Martin pointed it out, it is an issue of Chart.js not showing the chart when initiliazed in a hidden DOM element (its height and width remain at 0px even after showing the hidden element).

此处跟踪此问题.

如果您被初始化隐藏的选项卡等组件阻止,我将与您分享我的自制解决方案.我创建了一个指令,在其中编译 canvas 元素.为了能够在需要时(例如打开选项卡时)刷新元素,我会观察一个属性,我将在控制器中的选项卡更改时手动更改.

I share you my home made solution if you are blocked by components like tabs initialized hidden. I have created a directive in which I compile the canvas element. In order to be able to refresh the element when needed (eg when the tab is opened), I watch an attribute I will manually change on tab change in my controller.

这是我的指令:

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 更新时使用的有效解决方案.希望它可以帮助某人.

Dirty as hell, but this is a working solution you can use waiting for Chart.js update. Hope it can help someone.

相关文章