Angular JS中的双向数据绑定,用于使用HighCharts实现的图形

时间:2017-04-27 07:32:43

标签: angularjs highcharts 2-way-object-databinding

我正在尝试在AngularJS中为HighCharts编写一个指令,它支持双向数据绑定。单击HTML中的某个函数,我尝试使用新数据加载图形。

请检查下面的snipet。

HTML:

<hc-area-chart data="areaData"></hc-area-chart>
<button ng-click="updateGraph()">Update function</button>

控制器:

 angular.module('myModule', [])
        .directive('hcAreaChart', function () {
            return {
                restrict: 'E',
                template: '<div></div>',
                scope: {
                    title: '@',
                    data: '='
                },
                link: function (scope, element) {
                    Highcharts.chart(element[0], {
                        chart: {
                            type: 'area'
                        },
                        title: {
                            text: null
                        },
                        xAxis: {
                            categories: ['Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat', 'Sun']
                        },

                        plotOptions: {
                            pointStart: 4,
                        },
                        series: [{
                            showInLegend: false,
                            data: scope.data

                        }]
                    });
                }
            };
        })
        .controller('myController', function ($scope) {
            $scope.areaData = [0,6,5,7,5,4.5,10];

            $scope.updateGraphData = function () {
                console.log("inside update function");
                $scope.areaData = [10,20,30,40,50,60,70];
            }
        });

1 个答案:

答案 0 :(得分:1)

我认为你应该尝试这样的事情

      link: function (scope, element) {

            scope.$watch('data', function(){

                Highcharts.chart(element[0], {
                    chart: {
                        type: 'area'
                    },
                    title: {
                        text: null
                    },
                    xAxis: {
                        categories: ['Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat', 'Sun']
                    },

                    plotOptions: {
                        pointStart: 4,
                    },
                    series: [{
                        showInLegend: false,
                        data: scope.data

                    }]
                });

              })
            }