2016-09-16 61 views
0

我在我的應用程序中使用chart.js v2,因爲當我嘗試使用bower獲取最新版本時,它不會拉入dist文件夾,但那是另一個問題。chart.js v2.0.0重新繪製圖表

我已經爲這個插件創建了一個角度包裝,以將其包裝到我的應用程序中。 的包裝看起來是這樣的:

.controller('ChartController', function() { 
    var self = this; 

    // Create our chart 
    self.init = function (ctx, data, options, type) { 

     // Create our config 
     var config = angular.extend({}, { type: type || 'bar', data: data, options: options || {} }); 

     // Create our chart 
     self.chart = new Chart(ctx[0], config); 
    }; 
}) 

.directive('ngChart', function() { 
    return { 
     restrict: 'A', 
     controller: 'ChartController', 
     scope: { 
      data: '=ngChart', 
      type: '@', 
      options: '=' 
     }, 
     link: function (scope, element, attrs, controller) { 
      scope.$watch('type', function() { 
       controller.init(element, scope.data, scope.options, scope.type); 
      }); 
      scope.$watch('data', function() { 
       controller.init(element, scope.data, scope.options, scope.type); 
      }); 
     } 
    }; 
}); 

這是因爲你可以看到非常簡單。 在我的控制器我有這樣的:

self.reportType = 'raw'; 
self.reportTypes = [{ name: 'Raw data', type: 'raw' }, { name: 'Bar chart', type: 'bar' }, { name: 'Line chart', type: 'line' }]; 

在我看來,我有這樣的:

<div class="inputs"> 
    <div class="portlet-input input-inline input-small"> 
     <select class="form-control" ng-model="controller.reportType" ng-change="controller.test()" ng-options="type.type as type.name for type in controller.reportTypes"> 
     </select> 
    </div> 
</div> 

<div ng-if="controller.list.length && controller.reportType !== 'raw'"> 
    <div class="form-group"> 
     <button class="btn btn-default" ng-print><i class="fa fa-print"></i> Print</button> 
    </div> 

    <canvas class="print-only screen-only" ng-chart="controller.chartData" type="{{ controller.reportType }}"></canvas> 
</div> 

目前我只顯示在圖表上,如果類型是不生。 當我選擇它會繪製折線圖,​​如果我然後選擇酒吧它不會做任何事情。 我已經嘗試過所有的事情來重繪它,但它似乎並沒有工作。最新的建議是擴展配置(這是我在init方法中做的),以便創建一個副本,然後使用該配置副本創建一個新圖表。 這沒有奏效。

有誰知道我如何才能使它工作?

回答

0

我發現如果我修改了數據,圖表就會自行更新。 所以考慮到這一點,我改變了我的init()方法,以這樣的:

// Create our chart 
self.init = function (ctx, data, options, type) { 

    // Create our config 
    var config = { type: type || 'bar', data: angular.copy(data), options: options || {} }; 

    // Create our chart 
    self.chart = new Chart(ctx[0], config); 
}; 

和起作用的,它現在重繪正確。 我想這是因爲它必須檢查數據是否發生了變化,如果我做了副本,那麼它總是在變化。