AngularJS > Components

Directives in AngularJS

What is Directive in AngularJS?

Directives are markers on a DOM elements (HTML Tags, attribute, comment or CSS class) that tell compiler of AngularJS ($compile) to attach a specified behavior on these DOM elements or even transform them and its childrens.

In short, Directives are markers in the HTML tag that tells Angular to run or reference JavaScript code. Following are list of most of the directives in AngualarJS

  • ng-app – used to attach the application Module to the page or parent HTML element
  • ng-controller – used to attach a Controller function
  • ng-show / ng-hide -  used to show or hide a section based on the expression
  • ng-repeat – used to repeat a section for each item in an Array
  • ng-model – used to bind the element to the property value of the Model.
  • ng-init – used to initialize our data
  • ng-change – used to call a function when the element changes (input element inside form) <form ng-change=”compute()”></form>
  • ng-submit – used to call function when the form is submitted, it also automatically prevents the form doing its default post action to the server
  • ng-<event name> (ng-click/ng-dblclick) -  used to call a function on these events
  • ng-class – to set the class name, accepts the class name value as Boolean
  • ng-src – used to set the path for the image
  • ng-href – used to set the target url for the anchor tag
  • ng-cloak - used to hide elements till AngularJS bootstraps and finishes loading

AngularJs directives generally starts with ng however we can also prefix it with “data” like “data-ng-app”. So instead of writing ng-app, we can write data-ng-app.

We shall learn about these directives one by one in their separate posts.

Normalization of Directive formats

Generally directives are written dash delimited as an attribute to the HTML element, however it can also be written in following ways

    var app = angular.module("app", [])
    .controller("NormalizeController", function ($scope) {
        $ = "Sheo Narayan, TechFunda";

<div ng-app="app" ng-controller="NormalizeController">
    <p ng-bind="name"></p>
    <p ng:bind="name"></p>
    <p ng_bind="name"></p>
    <p data-ng-bind="name"></p>
    <p x-ng-bind="name"></p>

    <hr />
    <p class="ng-bind: name;"></p>

See the highlighted code snippet, where the ng-bind directive is written in following ways

  1. ng-bind - popular way to write directive
  2. ng:bind
  3. ng_bind
  4. data-ng-bind - suggested when HTML validation has to be performed for the app
  5. x-ng-bind
  6. class = "ng-bind: xxx;"

All these directives will have the same output.


Directive normalization in AngularJS

 Views: 20295 | Post Order: 6

Write for us

Hosting Recommendations