Which one is considered better:
- having a directive that interacts with services directly
or
- having a directive that exposes certain hooks to which controller may bind behaviour (involving services)?
Which one is considered better:
or
|
|||||||||
|
A directive is best (as a rule-of-thumb) when it's short (code-wise), (potentially) re-usable, and has a limited a scope in terms of functionality. Making a directive that includes UI and depends on a service (that I assume handles connection to the backend), not only gives it 2 functional roles, namely:
but also making it less re-usable, as you then can't use it again with another service, or with a different UI (at least not easily). When making these decisions, I often compare to the built-in HTML elements: for example However, this isn't the end of the story. Going beyond the analogy with the built-in HTML elements, you can create re-usable directives that both call services, and use a purely UI directive, just like it might use a
To code up the
Taking this to an extreme, you might not ever need to have a manual There is a downside I should mention: it gives more "moving parts" to the application, which adds a bit of complexity. However, if each part has a clear role, and is well (unit + E2E tested), I would argue it's worth it and an overall benefit in the long term. |
||||
|
Allow me to disagree with Michal Charemza answer. Although his answer is theoretically correct, it is not very practical for the real world. I am saying that because I used to think like that and tried to enforce it on a large real world app that myself and my team are building and it just became too troublesome. The analogy to the HTML language is not good, because you should not strive to build general purpose, extremely reusable directives, because you're not building a generic application like a web browser. Instead, you should use the directives to build a Domain Specific Language (DSL) for your app, that lives on its own domain. That does not mean that all directives should not be generic. Some might be, if it's in their nature. If you're building a custom date picker, by all means make it generic and reusable across apps. But if you're building something like a login box that binds to your back-end, just do it. The only rule of thumb should be: do not ever duplicate code (abstract little pieces to factories and services) and make it testable through dependency injection. Fortunately, with Angular, those are a piece of cake. Keep it simple. :) |
|||||
|