Search code examples
angularjsangular-directive

Angular directives support dependency injection, so why do they need controllers?


I was always under the impression that Angular Controllers on Directives were needed so you could 'hook up' the Directive to your domain/business logic.

Now I find out you can do DI straight into the Directive. My question is why did the Angular team bother to let you use Controllers on Directives as well when they didn't need to?


Solution

  • For one, you can use the require option to get access to a parent's controller, but not their directive code. This is really valuable when you have multiple directives cooperating to achieve something.

    Additionally, a properly-built controller may be able to be unit-tested independent of being attached to an element (which you'd have to do to test a full directive), so it's more convenient in some cases.