2

我正在尝试在 AngularJS 中为 HighCharts 编写一个指令,它支持两种方式的数据绑定以及图表上的单击事件。

指示:

app.directive('highchart', function () {
    return {
        restrict: 'E',
        template: '<div></div>',
        replace: true,
        link: function (scope, element, attrs) {
             scope.$watch(scope.example_chart, function() {
             var chart = JSON.parse(attrs.chart)
             element.highcharts(chart);
             }
        }
    }
});

现在,当我这样编写 HTML 时:

<div>            
     <highchart chart='example_chart'></highchart>
</div>

它支持点击事件,但不支持双向数据绑定。

并且,当它作为表达式传递时:

<div>            
     <highchart chart='{{example_chart}}'></highchart>
</div>

它支持两种方式的数据绑定,但是用 example_chart 的 JSON 编写的用于单击事件的函数没有被解析,因此无法运行。

因此,建议一种以AngularJS方式处理这两种情况的方法。

4

1 回答 1

3

highcharts-ng

您可以使用highcharts-ng指令,请参见此处的用法:Fiddle

您也可以使用自定义指令:

风俗

见演示Fiddle

实际上这里没有什么特别的,非常简单的隔离范围指令,在 highChart 配置(定义为 JSON)上带有观察者。

在我的情况下,我在特定领域使用了几个观察者来提高性能,但你可以对所有对象运行深度观察config


HTML

<high-chart config="chartConfig"> </high-chart> 

JS

myapp.directive('highChart',
   function () {
       return {
           restrict: 'E',
           replace:true,
            scope: {
            config: '='  
           },
           template: '<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>',
           link: function (scope, element, attrs) {

                var chart = false;

                var initChart = function() {
                  if (chart) chart.destroy();
                  var config = scope.config || {};
                  //var mergedOptions = getMergedOptions(scope, element, config);
                  chart = new Highcharts.Chart(config);

                  if(config.loading) {
                    chart.showLoading();
                  }

                };
                initChart();


       scope.$watch('config.loadRandomData', function (value) {
           if(value == false){return;}

           chart.series[0].setData(scope.config.series[0].data);          

           scope.config.loadRandomData = false;
        }, true);


        scope.$watch('config.loading', function (loading) {
          if(loading) {
            chart.showLoading();
          } else {
            chart.hideLoading();
          }
        });

       scope.$watch('config.series[0].type', function (type) {

         chart.series[0].update({type: type});        
        });

        scope.$watch('config.series[0].dataLabels.enabled', function (enableDataLabels) {          
         chart.series[0].update({dataLabels: {enabled: enableDataLabels}});        
        });                
         }//end watch           
       }
   }) ;

在此处输入图像描述

于 2014-10-17T07:25:09.470 回答