Search code examples
cssangularjstwitter-bootstrapnvd3.jsangular-nvd3

angular-nvd3 graphs' bad formatting when placed inside tab-content


I want to show piechart and multiBar chart on my webpage. I have a controller to set data and options for these charts. Everthing works fine except for the formatting of these charts. I have the following code:

<ul class="nav nav-tabs">
        <li class="active"><a data-toggle="tab" href="#pieChart">Pie Chart</a></li>
        <li><a data-toggle="tab" href="#multiBarGraph">Histogram</a></li>
      </ul>
      <div class="tab-content">
        <div id="pieChart" class="tab-pane fade in active">
          <nvd3 options='histOptions' data='histData'></nvd3>
          <p>Pie Chart</p>
        </div>
        <div id="multiBarGraph" class="tab-pane fade">
          <p>multiBarGraph</p>
          <nvd3 options='histOptions' data='histData' style="height:600px;"></nvd3>
        </div>
      </div>

I have this for navinagtion: enter image description here

Output is: enter image description here which is as desired. But as soon as i click on the navigation 'Histogram' to see another graph, I get this: enter image description here This graph is squeezed to one side of the screen. Now if I click on the graph or not another button to reload the data, the formatting changes like this: enter image description here This is what is actually desired.

Here if I reload the data(i have a button to do that) and go back to view my pieChart then i see this: enter image description here My pieChart has been squeezed now.

Each graph behaves fine when placed outside tab-content. I am clueless why this is happening. I need some suggestions. Thanks in advance.


Solution

  • After some research I found how to rectify this problem. This can be solved using refresh() function of nvd3

    Code:

    In html file:

    1)Add click function on the nav buttons

    <li class="active"><a data-toggle="tab" href="#pieChart" ng-click="refreshPie()">Pie Chart</a></li>
    <li><a data-toggle="tab" href="#multiBarGraph" ng-click="refreshHist()">Histogram</a></li>
    

    2)add api to each graph

    <nvd3 options='histOptions' data='histData' api="histApi"></nvd3>
    <nvd3 options='histOptions' data='histData' api="pieApi"></nvd3>
    

    In angular controller:

    1)refresh graphs inside functions(i.e. when nav button is clicked)

    $scope.refreshHist = function(){
    setTimeout(function(){
    $scope.histApi.refresh();
    },200);
    };
    
    $scope.refreshPie = function(){
    setTimeout(function(){
    $scope.pieApi.refresh();
    },200);
    

    Refreshing the graph corrects the formatting.