2013-04-29 76 views
4

使用AngularJS指令,我可以加載一個Highcharts圖。但是,我點擊一個點的事件處理程序沒有被執行。如何處理來自AngularJS指令的Highcharts事件?

http://plnkr.co/edit/pxU0IsBTrvcEwr2Znf5d?p=preview

JS

var app = angular.module('charts', []); 

app.directive('highchart', function() { 
    return { 
     restrict: 'E', 
     template: '<div></div>', 
     replace: true, 

     link: function (scope, element, attrs) { 

      scope.$watch(function() { return attrs.chart; }, function() { 

       if(!attrs.chart) return; 

       var chart = JSON.parse(attrs.chart); 

       $(element[0]).highcharts(chart); 

      }); 

     } 
    } 
}); 

function Ctrl($scope) { 
    $scope.example_chart = { 
     xAxis: { 
     categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] 
     }, 

     plotOptions: { 
     series: { 
      cursor: 'pointer', 
      point: { 
       events: { 
        click: function() { 
         alert ('Category: '+ this.category +', value: '+ this.y); 
        } 
       } 
      } 
     } 
     }, 

     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] 
     }] 
    }; 
} 

HTML

<section ng-app='charts'> 
    <div ng-controller="Ctrl"> 
     <highchart chart='{{example_chart}}'></highchart> 
    </div> 
</section> 
+2

我是一個AngularJS小白位,但注意到,更改爲'$(元素[0])highcharts(get_chart());'在$腕錶也可以正常工作。可能有助於確定根本原因。 – 2013-04-29 21:13:10

回答

3

看來,如果你直接這樣它的東西用JSON解析從屬性內的範圍內使用的數據進行工作。也許函數試圖以某種方式得到評估?使用圖表數據檢查屬性字符串後,您可以看到事件:函數包含空白對象。

plunker:http://plnkr.co/edit/QyccE0NDRfUCTuxTftUV?p=preview

+2

是的,就是這樣。我在角度IRC房間裏得到了一些幫助。使用範圍。$ eval相反是解決方案。 http://plnkr.co/edit/Vltj2czMzl0sApOwN7oX?p=​​preview – 2013-04-29 21:13:46