AngularJS Directives


AngularJS lets you extend HTML with new attributes called Directives.

AngularJS has a set of built-in directives which offer functionality to your applications.

It also lets you define your own custom directives.


About AngularJS Directives

AngularJS directives are extended HTML attributes with the prefix ng-.

  • ng-app – Initializes an AngularJS application.
  • ng-init – Initializes application data.
  • ng-model – Binds the value of HTML controls (input, select, textarea) to application data.

📖 Read about all AngularJS directives in our AngularJS Directive Reference.

Output :

Data Binding

The {{ firstName }} expression, in the example above, is an AngularJS data binding expression.

Data binding in AngularJS binds AngularJS expressions with AngularJS data.

{{ firstName }} is bound with ng-model="firstName".

In the next example, two text fields are bound together using two ng-model directives:

Output :

Repeating HTML Elements

The ng-repeat directive repeats an HTML element:

Output :

The ng-app Directive

The ng-app directive defines the root element of an AngularJS application.

It will auto-bootstrap (automatically initialize) the application when a web page is loaded.


The ng-init Directive

The ng-init directive defines initial values for an AngularJS application.

Note: Normally, you will not use ng-init. Instead, you will use a controller or module.

You will learn more about controllers and modules later.


The ng-model Directive

The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

The ng-model directive can also:

  • Provide type validation for application data (number, email, required).
  • Provide status for application data (invalid, dirty, touched, error).
  • Provide CSS classes for HTML elements.
  • Bind HTML elements to HTML forms.

Read more about the ng-model directive in the next chapter.


Create New Directives

In addition to all the built-in AngularJS directives, you can create your own directives.

New directives are created by using the .directive function.

To invoke the new directive, make an HTML element with the same tag name as the new directive.

When naming a directive, you must use a camelCase name, like w3TestDirective, but when invoking it, you must use a kebab-case name: w3-test-directive.

Output :

Restrictions

You can restrict your directives to only be invoked by certain methods.

Output :