Stop Writing AngularJS Directives!
I see it time and time again. A new developer comes to Angular. She wants to, say, display a list of things and a button that sorts them. So she asks her fellow—more Angular savvy—colleagues how on earth to do that.
Write a directive, they say. Your logic will be encapsulated and reusable, they say.
Know what? Don’t. You heard me. Don’t write a directive.
If you do, hours of headache and desperate googling later, you’ll have some half-baked code that either depends directly on its parent controller’s state (there goes reusability and encapsulation), or you’l be completely at a loss about how to access anything in the directive’s isolated scope. And don’t even get me started on transclusions.
Directives in Angular are complicated, doubly so if you’re a newbie and you don’t know what you’re doing (and in Angular, that will take you a while). Oh and I should mention when you botch a directive, you usually won’t get errors in the console. Or you will but they’ll be weird Angular errors which you won’t understand. Most of the time, though, you will just get the scoping wrong and you won’t see any errors at all; your code will just happily not do what you want it to do.
Okay, so what should I do?
Don’t jump the gun.
You’d be surprised by how much you can achieve with controllers and directives baked into Angular. TodoMVC is written almost entirely using built-ins. Look at ng-model and filters. Learn how to use ng-repeat. They’re pretty powerful. If you need more, take a look at AngularUI or Ionic (if you’re writing a mobile app). And if you can’t find what you want there, use Google or DuckDuckGo or whatever your favorite search engine is because chances are someone has already written what you need.
Then, when you find it, grab the source code, make yourself a cup of some caffeinated beverage and read it through. Understand how it works. Figure out how it uses isolated scope and scope inheritance. One of the greatest things about the JavaScript world is that almost everything is open source. Which basically means you can tap into other people’s brains. So go and absorb the heck out of that directive’s code. It will make you smarter.
And then—only then—sit down and write your own directive. That is, if you still want to. It may well turn out you don’t need to spend time making that particular piece of code reusable.
So save yourself the headache and think twice before you bang out your own directive.