且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Highchart角度指令不会从动态(ajax)数据表重绘

更新时间:2023-02-05 19:22:08

好的。我设法让它工作。我认为问题在于,Highcharts没有意识到这些变化,或者是否知道这些变化,那时DOM还没有完成渲染。这是代码的工作版本。

Ok. I managed to get it to work. I think the problem is that, Highcharts does not aware about the changes or if it knows about the changes, the DOM at that moment hasn't finish rendering. This is the working version of the code.

指令:

Directive:

app.directive('highchart', function($parse, $timeout) {
    return {
        restrict: 'E',
        template: '<div></div>',
        replace: true,
        link: function(scope, element, attrs) {
            var config = $parse(attrs.config)(scope);
            $(element[0]).highcharts(config);

            scope.$watch(attrs.watch, function(newVal) {
                if (newVal) {
                    var complete = function (options) {
                        var chart = $(element[0]).highcharts();
                        // capture all available series
                        var allSeries = chart.series;
                        for (var i = 0; i < allSeries.length; i++) {
                            allSeries[i].setData(options.series[i].data, false);
                        }

                        chart.redraw();
                    };

                    // doesn't work without the timeout 
                    $timeout(function() {
                        Highcharts.data({
                            table: config.data.table,
                            complete: complete
                        });   
                    }, 0);
                }
            });
        }
    };
});

在控制器中,我们可以设置配置。

In controller, we can setup the config.

    $scope.chartConfig = {
         // config here
    };

使用它:

To use it:

<highchart config="chartConfig" watch="levels"></highchart>

其中属性 config 绑定到$ $ scope.chartConfig watch watch的触发器$ scope() code>在指令中。当控制器中的 $ scope.levels 更改时,它会重新呈现图表。

where the attribute config is bind to the $scope.chartConfig and watch is the trigger for watch.$scope() in the directive. When $scope.levels changes in controller, it would re-render the chart.

实际上我没有比如指令依赖于我现在拥有的 watch 属性,但我不确定***或其他方式是做什么的。如果有人有更好的主意,请让我知道。

I don't actually like the dependency of the directive to the watch attribute that I have right now, but I'm not sure what is the best or other way to do this. If anyone have a better idea, do let me know.

请注意,这只会将表格转换为高图。对于其他人,您可能需要使用其他angularjs highcharts指令。

Please note that this will only work to convert table to highchart. For others, you might need to use other angularjs highcharts directive.