7

i want to use D3.js v4 with AngularJS 1.5x

In the past i used .directives for the charts, but now i was wondering if it's possible use .components instead of directives, and if it's a good practice.

Check the sample case on Plunkr

The problem appears with the d3.select(element[0]).append('svg') within components. The console throw an error: element is not defined.

so i tried with something like d3.select('chart-container').append('svg') but then d3 inject all the charts in the first element which own that class ( look for the class in all the document, not only the component ).


So... can someone help me to do a right d3.select() for a reusable component ?

without add different ID's for each one ( too much work and too hard for maintain )

Héctor León
  • 2,210
  • 2
  • 23
  • 36
  • Hey, what is wrong with using directive? You can have controller for directive. – terafor Aug 18 '16 at 09:15
  • 1
    Just trying to do it in the Angular 2 way, for a easier transition in the future, anyway there should be a way to tell d3 - "Select THIS div only in the component, don't look outside ! " – Héctor León Aug 18 '16 at 09:18

1 Answers1

8

You can pass $element to component controller

svg     = d3.select($element[0]).append('svg'),

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

terafor
  • 1,620
  • 21
  • 28
  • 1
    Hi, thanks for your reply. interesting, this select the component itself and append it, but can i point to the div inside of the component template ? You know, for a specific location where to append it – Héctor León Aug 18 '16 at 09:25
  • Sure - just always look for it relative to the `$element`, the same way you would in a directive. – Ethan Jewett Aug 18 '16 at 14:29