Highcharts:Formatter和click功能不适用于Angular

时间:2015-03-27 20:49:09

标签: javascript angularjs events highcharts formatter

我正在尝试格式化我的工具提示并在我的highcharts图上添加一个on click事件,但是注意到它只有在我以某种方式创建图形时才有效(不使用angular $ scope)。是否有理由使用$ scope创建图表和这些函数?

例如,这不起作用:

$scope.defaultChart = {

                xAxis: {
                    categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
                        'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
                },

                tooltip: {
                    formatter: function () {
                        return "This doesn't work";
                    },
                    shared: true
                },


                plotOptions: {
                    series: {
                        cursor: 'pointer',
                        point: {
                            events: {
                                click: function () {
                                    alert("This is also broken");
                                }
                            }
                        }
                    }
                },

                series: [{
                    data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
                }, {
                    data: [216.4, 194.1, 95.6, 54.4, 29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5]
                }]
            });

但这很好:

$('#container').highcharts({

                xAxis: {
                    categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
                        'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
                },

                tooltip: {
                    formatter: function () {
                        return 'This works';
                    },
                    shared: true
                },


                plotOptions: {
                    series: {
                        cursor: 'pointer',
                        point: {
                            events: {
                                click: function () {
                                    alert("This function works too");
                                }
                            }
                        }
                    }
                },

                series: [{
                    data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
                }, {
                    data: [216.4, 194.1, 95.6, 54.4, 29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5]
                }]
            });

为什么会这样?

1 个答案:

答案 0 :(得分:1)

问题最终导致指令中的highcharts选项被JSON.parse(JSON.stringify(obj))克隆,它无法复制函数。

我把它改为:

function cloneObject(obj) {
    if (obj === null || typeof obj !== 'object') {
        return obj;
    }

    var temp = obj.constructor(); // give temp the original obj's constructor
    for (var key in obj) {
        temp[key] = cloneObject(obj[key]);
    }

    return temp;
}

现在功能正常。