Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is directive in Angular.JS

Tags:

angularjs

I have a hard time understanding directives in AngularJS. The definition by AngularJS themselves is confusing at best:

Directives are a way to teach HTML new tricks. During DOM compilation directives are matched against the HTML and executed. This allows directives to register behavior, or transform the DOM.

Could someone explain directives in AngularJS in plain English commonly used in teaching programming. Something like: directives are funcions/objects that extends ...

like image 429
AdamNYC Avatar asked Feb 02 '13 14:02

AdamNYC


2 Answers

They are a way to extend HTML, adding new elements and/or adding new attributes to existing elements. From Angular's developer guide:

A directive is a behavior or DOM transformation which is triggered by the presence of a custom attribute, element name, or a class name. A directive allows you to extend the HTML vocabulary in a declarative fashion.

You can use them either for adding behavior to HTML, defining a link function that keeps bidirectional binding between variables belonging to scopes and DOM elements, or for dynamically manipulating DOM, defining a compile function that can modify or even generate new DOM elements and attributes. Consider it a way of extending HTML and transforming it into a Domain Specific Language.

like image 170
remigio Avatar answered Oct 07 '22 00:10

remigio


Directives can be attributes, tags or even class names.

Once you write them in your HTML markup, it gets picked up by angular and acts the way you defined it.

It gives you the ability to define new custom HTML elements like or , or new behavior attributes like

<div angry></div>

And whenever someone will click on that div he will get and alert with "I'm Angry".

You can basically do every extension you need in order to make your html as lean and understandable as possible. it all depends with how you define you directive.

like image 44
Shai Reznik - HiRez.io Avatar answered Oct 06 '22 23:10

Shai Reznik - HiRez.io