天天看點

Intergate flot with Angular js ——Angular 圖形報表

下面這篇文章最終的結論就是 Flot 插件 結合 Angular 的Directive 來處理 圖表的繪制

給出github上的一個demo源碼。https://gist.github.com/flyysr/ba3a51cdbfcae7f53dec 

最近項目中遇到了要顯示圖形報表的問題,項目的前端架構主要是基于 AngularJs 的,故,找js插件來顯示圖表(chart).

找到了Flot (http://www.flotcharts.org/), 說明一下,Flot是一個繪制圖表的Js庫。

下面問題的關鍵是怎麼将 Flot和 Angular 整合起來。

----------------------------------------------------

顯然,繪制圖表涉及到大量的 DOM操作,而Angular的 Directive是有關html自定義标簽的,是以這裡的整合主要的用到 Angular的Directive的知識。

下面是我在StackOverflow上搜到的類似的提問:

I am new to Angular and Flot, but am experienced with Jquery and Javascript. I am a bit confused about how to go about binding a Flot chart to Angular data models, since Flot is a JQuery plugin. I've searched around, but haven't been able to find an example.

I would also be happy to use highcharts, google-charts(這幾個也是js繪制圖表的插件), or any other charting solution.

下面的是 stackOverflow上的最佳答案,這裡記錄之。

1、Since charting involves heavy DOM manipulation, directives are the way to go.

2、Data can be kept in the controller

App.controller('Ctrl', function($scope) {
    $scope.data = [[[0, 1], [1, 5], [2, 2]]];
});
      

 And you create custom html tag (Can be an attribute too) specifying the model you want to get data from.

<chart ng-model='data'></chart>
      

  which angular can compile through a  directive.

App.directive('chart', function() {
    return {
        restrict: 'E',
        link: function(scope, elem, attrs) {
            var data = scope[attrs.ngModel];
            $.plot(elem, data, {});
            elem.show();
        }
    };
});
      

Example here  

This process is similar for most plugins that modify the DOM.

Also, you can watch for changes in the chart's underlying data and redraw it, so this way you can grab data through the $http service from your controller and update the view automatically. This can be achieved by modifying the linking function in the directive definition object

var chart = null,
       opts  = { };

    scope.$watch(attrs.ngModel, function(v){
        if(!chart){
            chart = $.plot(elem, v , opts);
            elem.show();
        }else{
            chart.setData(v);
            chart.setupGrid();
            chart.draw();
        }
    });
      

  Notice the usage of  Flot's  API  within the directive to achive what we want .

Here the full Example