drbishop drbishop - 4 months ago 34
Javascript Question

Using directive scope to update Highcharts

I have two charts with different

ids
(
#chart1
and
#chart2
). I've created a button, so I can change a chart's type (e.g. from column to line):

<button ng-click="updateChart(name, 'line')">Line</button>


This button calls the
updateChart
function:

$scope.updateChart = function(id, type) {
var chart = $('#' + id).highcharts();
chart.series[0].update({
type: type
});
};


As I need to call the button for every chart, I've created a directive passing a
name
value to the scope:

.directive('changeChart', function() {
return {
restrict: 'E',
scope: {
name: '@'
},
templateUrl: "change-chart.html"
};
})


In my HTML I call the directive passing the chart id:
<change-chart name="chart1"></change-chart>


However, the button isn't working. It only works if I remove the directive scope and set the
id
manually. Any ideas on how to solve this?

Here's a Plunker: http://plnkr.co/edit/5wmLldmXpoq9wiMACbNS?p=preview

Answer

That is because when you define a scope object in your directive, it creates an isolate scope for that directive. That means, the scope within your directive cannot access the scope properties defined outside. You have your controller defined on the outer scope where you attach the function updateChart. So, your isolate scope directive is not aware of this method.

To fix this, you can define a controller on your directive itself. And in that controller, define the method updateChart

.directive('changeChart', function() {
  return {
    restrict: 'E',
    scope: {
        name: '@'
    },
    controller: function ($scope) {
        $scope.updateChart = function(id, type) {
            var chart = $('#' + id).highcharts();
            chart.series[0].update({
                type: type
            });
        };
    },
    templateUrl: "change-chart.html"
  };
})