Highcharts无法使用angular.js更新图表

时间:2016-06-02 10:02:23

标签: angularjs highcharts

我正在开发一个使用Highcharts和Angularjs并使用SignalR获取数据的项目。问题是饼图正确初始化但无法使用来自服务器的数据更新图表。这是我的代码:

'use strict';

angular.module('mbCharts').directive('mbGauge', [
    'mbWebMetricsService',
    function (mbWebMetricsService) {
        return {
            //
            // scope is inherited from the widget using this directive
            //
            templateUrl: '/ext-modules/mbCharts/mbGaugeTemplate.html',

        link: function (scope, el, attrs) {
           Highcharts.chart(el[0], {
                chart: {
                    type: 'pie'
                },
                title: {
                    text: scope.title
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        dataLabels: {
                            enabled: true,
                            format: '<b>{point.name}</b>: {point.percentage:.1f} %'
                        }
                    }
                },
                series: [{
                    data: [{
                        name: "Microsoft Internet Explorer",
                        y: 100
                    }, {
                        name: "Chrome",
                        y: 0,
                        sliced: true,
                        selected: true
                    }]
                }]
            });

            // locate the widget showing this gauge
            var widget = el.closest('.gridster-item');


            // monitor the widget's size
            widget.resize(function () {
                //if (scope.chart != null) {
                //    scope.chart.chartWidth = widget.width();
                //    scope.chart.chartHeight = widget.height();
                //}                    
            });

            //scope.title = mbWebMetricsService.getTitleForMetric(scope.metric);
            scope.title = "CPU percentage";
            scope.initialized = false;

            scope.$on('mbWebMetricsService-received-data-event', function (evt, data) { 
                var val = Math.round(data[scope.metric]); 
                scope.chart.series[0].data[0].y = val;
                scope.chart.series[0].data[1].y = 100 - val;
            });
        }
    };
}
]);

1 个答案:

答案 0 :(得分:1)

问题是您希望如何更新数据。它不是要更改图表对象中的选项,而是使用适当的API。要更新积分,请使用chart.series[index].data[pointsIndex].update()

因此,在您的情况下,首先存储图表对象:

var myChart = new Highcharts.Chart(el[0], { ... });

然后更新积分:

scope.$on('mbWebMetricsService-received-data-event', function (evt, data) { 
  var val = Math.round(data[scope.metric]); 
  myChart.series[0].data.update(val);
  myChart.series[0].data.update(100 - val);
});