Problems Injecting DOM Elements from Angular Views into D3 Objects

I was having a hell of a lot of gotchas related to redrawing a D3 chart within an Angular view. It was looking like something on the Angular side was causing my DOM references to break. Maybe ng-route redrawing views?

That was bad, because my charts were being appended to a DOM element that had been passed from Angular over into D3 via a config object. It worked before changing routes, but when you toggled through routes and returned to the chart, it couldn't be redrawn.

The fix was to stop passing in a reference to the element. Pass in a selector string. Just set the ID on the element, and then find it via

This took a while to fix because, at some level, I'd switched from the select('#foo') camp to the "never use IDs in web apps" camp.

The lesson learned is simple: sometimes, Angular is going to make it hard to use references to DOM elements, so you need to resort to using selector strings.

More generally: use a higher-level interface to select lower-level objects. These higher-level interfaces are probably more stable over time, too.