Angular Directive Basics

Angular Directive Basics

At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS’s HTML compiler ($compile) to attach a specified behavior to that DOM element (e.g. via event listeners), or even to transform the DOM element and its children.

AngularJS comes with a set of these directives built-in, like ngBind, ngModel, and ngClass. Much like you create controllers and services, you can create your own directives for AngularJS to use. When AngularJS bootstraps your application, the HTML compiler traverses the DOM matching directives against the DOM elements.

Matching Directives

Before we can write a directive, we need to know how AngularJS’s HTML compiler determines when to use a given directive.

Similar to the terminology used when an element matches a selector, we say an element matches a directive when the directive is part of its declaration.

In the following example, we say that the <input> element matches the ngModel directive

<input ng-model=”foo”>

The following <input> element also matches ngModel:

<input data-ng-model=”foo”>

And the following <person> element matches the person directive:

<person>{{name}}</person>

Normalization

AngularJS normalizes an element’s tag and attribute name to determine which elements match which directives. We typically refer to directives by their case-sensitive camelCase normalized name (e.g. ngModel). However, since HTML is case-insensitive, we refer to directives in the DOM by lower-case forms, typically using dash-delimited attributes on DOM elements (e.g. ng-model).

The normalization process is as follows:

Strip x- and data- from the front of the element/attributes.
Convert the:, -, or _-delimited name to camelCase.

IT Professionals, Web Developers, Web Programmers, IT students can Apply for the certification course to move ahead in their careers.

Angular 4 Tutorial IndexBack to Angular 4 Tutorial Main Page

Share this post
[social_warfare]
Angular Directives
Component or Directives

Get industry recognized certification – Contact us

keyboard_arrow_up