AngularJS Directives, Demystified
First thing to grasp in AngularJS is that it's not a jargon. Every concept in Angular is already there in JavaScript or in other libraries. Keep reading.
What is a Directive in AngularJS?
Well, according to AngularJS documentation Directives are Marker such as Element, Attribute, CSS class or even comment in the DOM element which tell HTML compiler to attach specific behaviour to DOM element or even modify them.That sounds good, but how is it possible to create a custom HTML. Something like
<superman></superman>.
Well there is a provision in HTML 5 to create a custom element, which you can learn here.Saying that, it is very easy to define our own custom element by simply creating a new directive and restricting it to "E", i.e. Element.
We will learn more in the later post where I'll show you how to create your own Directives. Other than element directives you can create an attribute directive or a class directive or comment directive.
Directive tells the compiler to attach the specific behaviour. For example you would select a class "slider" and attach the special method called "horizontalSlider" in jQuery to retrieve the properties of the element and append the images retrieved using the AJAX.
$(".slider"). horizontalSlider();
Where $ is the jQuery object and horizontalSlider is method in that object. Similarly, in Angular we directly build the custom element to attach the behaviour. Where creating an element is a new feature.
Following is the animation which will explain how does Angular compiles or parses the DOM to find the directives. Follow the blue cursors and bottom terminal to know the current state of the parser. Start reading when Terminal says HTML Compiler > init.
Disclaimer: This is just the representation for the sake of explanation, the actual process may be different.
The directives which you are seeing in above animation are default directives of AngularJS. Following are few of the common directives we will come across.
- ng-app
- ng-controller
- ng-model
- ng-init
- ng-bind
- ng-view
- ng-click
At this point I guess, you are good to go with the directives. Let's dive into the official documentation for directives here.
The one which you see in double curly braces
{{}}
are expressions. Which we will see later.