Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

javascript - Chart.js in AngularJS tabset does not render

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>

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

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

This issue is tracked here.

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.

Here is my directive :

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...