4

Using an AngularJS directive, I am able to load a Highcharts graph. However, my event handler for clicking on a point is not being executed.

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>
Sean Cain
  • 898
  • 2
  • 10
  • 16
  • 2
    I am bit of an AngularJS noob, but noticed that changing to `$(element[0]).highcharts(get_chart());` in the $watch makes it work. Might help determine the root cause. – Dan Liebster Apr 29 '13 at 21:13

1 Answers1

3

It seems to be working if you use the data from the scope directly so it's something with JSON parsing from within the attribute. Perhaps the function tries to somehow get evaluated? After examining the attribute string with the chart data, you can see the event: function contains blank objects.

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

Bogdan Rybak
  • 2,107
  • 1
  • 19
  • 22
  • 2
    Yep that was it. I got some help in the angular IRC room. Using scope.$eval instead was the solution. http://plnkr.co/edit/Vltj2czMzl0sApOwN7oX?p=preview – Sean Cain Apr 29 '13 at 21:13