Search code examples
javascriptangularjsd3.jsangular-directive

AngularJS: Using a custom javascript function defined elsewhere in controller/directive


So, I have javascript file (kind of a library, still working on it) 'linechart.js' which holds an object which in turn contains a function that takes some data as input and generates a line chart using D3. Here's the code:

linechart.js

var lineobj = {
   plotFunc : function(data) {
        //generate line chart using the data argument
   }
} 

The data which is passed to the object described above is actually generated in an angularjs controller as follows:

index.controller.js:

app.controller('MainCtrl', ['$scope', function($scope) {
    $scope.generateData = function(){
        //generate data for the line chart
    }
}])

Now, the problem I am facing is a problem of approach.

Here are my queries:

1. What is the best way to pass data to linechart.js so that it can generate the linechart.

2. Should I use a directive and call the function 'plotFunc' to generate the linechart? If so, how do I call the function?

3. Should I call the function in the controller itself? If so, again how do I call the function?

4. Is there any other better method that I have not mentioned?


Solution

  • Best way would actually to generate a service which wraps D3, require that in your controller and then you can call the methods. There are some good libraries for charting which already wrap D3 like nvd3, otherwise take a look into this link which explains pretty good how you can wrap D3 with Angular.js

    http://www.ng-newsletter.com/posts/d3-on-angular.html