Controller or Link on an Angular directive
December 22, 2014
Came across a big gotcha moment today. Turns out, controllers aren’t supposed to be used for DOM manipulation of a directive; they’re only intended for reusable directive logic. I found this out the hard way on a tooltip directive by inject $element, and expecting it to be whichever element I put the directive on. Problem is, the controller is only ever instantiated once, so it bound to the first element I put it on. I ended up using the compile function, since I needed to modify how the element compiles, otherwise I’d have used the link function.
To test all the logic independently of the directive still, I created a factory that provided a controller, and instantiated it in the compile function, taking in scope, element and attributes.
Hey, I'm Ian. I build websites and write about what I learn as I go. Follow me on Twitter.