Directives are the markers on DOM element which are used to specify behavior on that DOM element. All AngularJS directives start with the word “ng”. There are many in-built directives in AngularJS such as “ng-app”, “ng-init”, “ng-model”, “ng-bind”, “ng-repeat” etc.
- ng-app
The ng-app directive is the most important directive for Angular applications. It is used to locate the beginning of an Angular application for AngularJS HTML compiler. It marks the HTML elements that Angular intends to make the root element of the application. The custom attributes use spinal-cases, whereas the corresponding directives follow the camelCase. If we do not use this directive and try to process other directives, it gives an error. - ng-init
The ng-init directive is useful for initializing the data variable’s inline statement of an AngularJS application. Therefore, those statements can be used in the specified blocks where we can declare them. A directive ng-init is like a local member of the ng-app directive, and it may be a single value or a group of the values. It directly supports JSON data. - ng-model
The ng-model directive binds the values of HTML elements such as input, select, textarea to the application data. It provides two-way binding behavior with the model value. Sometimes, it is also used for databinding. - ng-bind
The ng-bind directive is used to bind the model/variable’s value to HTML controls of an AngularJS application. It can also be used with HTML tags attributes like:, and more but it does not support two-way binding. We can only check the output of the model values. - ng-repeat
The ng-repeat directive is used to repeat HTML statements. It works the same as for each loop in C#, Java or PHP on a specific collection item like an array. - In AngularJS, directives are special markers on a DOM element that tell AngularJS to attach a behavior to that DOM element or even transform the DOM element and its children. AngularJS comes with a set of built-in directives, and you can also create custom directives.
Some commonly used built-in directives in AngularJS include:
- ng-app: Defines the root element of an AngularJS application.
- ng-controller: Attaches a controller class to the view.
- ng-model: Binds an input, select, or textarea element to a property on the model.
- ng-bind: Binds the content of an HTML element to a model property.
- ng-repeat: Iterates over a collection (such as an array or object) and repeats a set of HTML elements for each item.
- ng-show/ng-hide: Shows or hides an element based on a given expression.
These are just a few examples, and AngularJS provides several other directives for various purposes. Custom directives can also be created using the
directive
function, allowing you to encapsulate and reuse specific behaviors or components in your application