AngularJS outputting Javascript in a directive

72 Views Asked by At

Hi good people of stack overflow..

I am trying to make a directive in angular that outputs javascript that I'll use to draw a morris chart. So far I've been having a tough time. Here's the code:

area-chart.js:

angular.module('areaChart', ['ui.bootstrap']).directive('areaChart', function() {
var directive = {};
directive.templateUrl = directivePath + '/charts/area-chart.html';
directive.restrict = 'EA';
directive.scope = {
    dealership: "=",
    chartdata: "="
};

directive.controller = function($scope) {
    $scope.ykeys = function() {
        var ykeys = [];
        angular.forEach($scope.chartData, function(d,k) {
            if(k != 'period') { ykeys.push(k); }
        });
        return "'" + ykeys.join("','") + "'";
    }
}

return directive;
});

And, area-chart.html

<script>
Morris.Area({
    element: 'area-chart-fuckyou',
    xkey: 'period',
    ykeys: [{{ ykeys }}],
    labels: [{{ ykeys }}],
    hideHover: 'auto',
    pointSize: 2,
    resize: true,
    data: 'fuckyou' 
});
</script>

I get an unexpected token '{' error any time i try to use angular substitution in the outputted javascript. So, where I try to inject {{ykeys}} it throws the error. I've tried changing {{ykeys}} to include the full string that I'd want in there IE having it return ['key1','key2'] and all combinations thereof. I guess I don't understand what the order of operations is for angular. Can anybody help me?

1

There are 1 best solutions below

0
On BEST ANSWER

You need to add link function that will do the chart initialization

directive.link = function(scope, element, attrs){
  new Morris.Area({
      element: element, //here you can attach direct element
      data: scope.data,
      ykey: scope.ykeys()
      labels: scope.ykeys(),
      hideHover: 'auto',
      pointSize: 2,
      resize: true,
      data: 'fuckyou' 

  });
}