Directives in AngularJS

Directives in AngularJS helps in extending the power of HTML.

The important responsibilities of directives are

  1. DOM manipulation [ng-show]
  2. Relieving view events  [ng-click]
  3. 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

  1. Link function of the directive to define how the directive should behave.
  2. Create a Directive Controller and put the logic.

Directives in your View/HTML can be written as:

  1. Element Names or Tags (E)
  2. Attributes (A)
  3. Classes (C)
  4. 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:

  1. Angular doesn’t complain if there are multiple directives with the same name declared on a page.
  2. 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.
  3. Changing the order of the directive declarations having the same name impacts your output.
  4. Hence its vital to name directives uniquely.

My next post will talk more about

Requiring Directives within another and isolation of scope.