AdamNYC
AdamNYC

Reputation: 20435

What is directive in Angular.JS

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 ...

Upvotes: 6

Views: 5773

Answers (3)

Deepak Khantwal
Deepak Khantwal

Reputation: 11

AngularJS Directives are a combination of HTML template markup (i.e. attributes, elements and CSS class) and supporting the JavaScript code. The angularJs JavaScript code defines the html data and behavior of the html element.

AngularJs directive are use to extend the HTML vocabulary i.e they decorate the html elements with new behavior and help to manipulate html elements attributes in interesting way.

There are some built-in directives provided by AngularJS like as ng-app, ng-controller, ng-repeat, ng-model etc

Upvotes: 0

Shai Reznik - HiRez.io
Shai Reznik - HiRez.io

Reputation: 8948

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.

Upvotes: 4

remigio
remigio

Reputation: 4211

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.

Upvotes: 9

Related Questions