Directives in AngularJS helps in extending the power of HTML.
The important responsibilities of directives are
- DOM manipulation [ng-show]
- Relieving view events [ng-click]
- Widgets [via custom directives]
AngularJS provides a set of build in directives like ng-bind, ng-class etc.
Custom Directives can also be written quite easily. We can either use
- Link function of the directive to define how the directive should behave.
- Create a Directive Controller and put the logic.
Directives in your View/HTML can be written as:
- Element Names or Tags (E)
- Attributes (A)
- Classes (C)
- HTML Comments (M)
(E, A C or M are restriction types)
Note : Angular normalizes an element’s name or tag to map elements and directives. More details can be found here.
Custom Directive Code Snippet:
Few important points to note here:
- Angular doesn’t complain if there are multiple directives with the same name declared on a page.
- While loading the Dynamic DOM, Angular compiles all the directives [including ones with same name as in our examples] but only executes the first directive.
- Changing the order of the directive declarations having the same name impacts your output.
- Hence its vital to name directives uniquely.
My next post will talk more about
Requiring Directives within another and isolation of scope.