Components and directives in angular 1.5
The .component DOES NOT replaces .directive like @rek Żelechowski said. So..
There’s nothing you can do with .component() that you can’t do with .directive(). It aims to simplify the way we create “components” – which roughly means UI directives.
When can/should you use it?
Clearly there are a few cases where you can’t/shouldn’t use it:
- If you need the link function (though you rarely should)
- If you want a template-less directive, e.g. ng-click that doesn’t have a template or separate scope
For all your other directives, this should work. And because it saves on boilerplate and less error-prone it’s nicer to use.
Despite of all new goodies, .component() can’t fully replace .directive().
The .component
is now preferred way of writing code because it favors good practices and gives developers ability to write code like in angular 2 (similar to Web Components). Basically, when you write code using component
, upgrading to angular 2 will be easier. Functionalities remains almost the same. You should use .component
always when it is possible.
Changes (extract)
- component is declared using object instead of function
- simplified isolated scope using
binding
property - components are always with isolated scope
- some bad practices will not be possible
- simpler, easier to understand configuration
- lifecycle hooks: (
$onInit()
,$onChanges(changesObj)
,$doCheck()
,$onDestroy()
,$postLink()
)
Awesome article is here: https://toddmotto.com/exploring-the-angular-1-5-component-method
When not to use Components (from docs):
- for directives that need to perform actions in compile and pre-link functions, because they aren't available
- when you need advanced directive definition options like priority, terminal, multi-element
- when you want a directive that is triggered by an attribute or CSS class, rather than an element.
I believe, that the best description you can find is official guide: https://docs.angularjs.org/guide/component. It covers all changes, reasons for changes and gives you deep understanding of the components.
EDIT 01-2020:
I don't work on ng1 code anymore since at least a year
At the point of writing response (01-2017), impression that they are going to replace directives in most scenarios was correct. I removed a word "replaced" from the answer in 06-2017, because it is was indeed misleading at that point in time. However, since 1.5 you should still prefer components over directives when possible.
Actually, you should prefer not to use AngularJS at all. It is now in LTS and basically, only errors will be fixed. No new features. Also, LTS ends on 01-07-2021. https://docs.angularjs.org/misc/version-support-status#long-term-support
PS. Using component instead of directive makes the code easier to port to ngx in the future.