How to Integrate Flot with AngularJS?

我的梦境 提交于 2019-11-27 10:48:12
jaime

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

Data can be kept in the Controller

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

And you can create a custom HTML tag1 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 achieve what we want.

Here the full example


1 Can be an attribute too.

To use jQuery plugins with angularJS, you have to wrap them in directives, you can find some exemples of jQuery plugins directives by reading the source code of angularUI directives: https://github.com/angular-ui/angular-ui/tree/master/modules/directives

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!