AngularJS Directives

AngularJS Directives

HTML tags uses directives as attributes or custom tags. It tells AngularJS's HTML compiler ($compile) to attach a behavior or transform that DOM elements (via event listener). Its somehow complicated to understand but too easy in using. It is used to attaching Controllers and $scope objects.  By using directives we can achieve good functionality with writing less code.

How directives are working actually?

Matching directive element in HTML by AngularJS's compiler.

<!-- input element matches ngModel directive -->
<input ng-model="">

<!-- input element also matches ngModel directive -->
<input data-ng-model="">

<!-- element matches custom directive person -->


Angular normalizes the directive attribute and element's name to match.

Read carefully and remember, AngularJS refers the directive name by case-sensitive camelCase in (example ngModel) in JavaScript. As per W3C standards HTML DOM is case-sensitive in lower-case forms in HTML. So AngularJS is using dash-delimited attributes in DOM elements (example ng-model).

The normalize process works in both ways to match the directive
1. Removes the "data-" from "data-ng-model" front-end attributes (HTML)
2. convert the "-" dash-delimited to camelCase in beck end (JavaScript)

Commonly used Directives

  • ngApp - used to initialize framework.
  • ngController - it contains the business logic for single view through $scope object.
  • ngModel - used to binding $scope object to an input, textarea, select and other custom from controls.
  • ngBind - used to binding $scope object to HTML elements. {{ }} expression directives are better alternate.
  • ngRepeat - creating single template instance for each item in data collection array with own scope with $index key.
  • ngSubmit - run function on form onsubmit event.
  • ngInclude - used to insert HTML template in view.
  • ngClick - it assign the click event to HTML elements.
  • ngShow - it shows or hide an HTML element conditionally.
  • ngHide - it shows or hide an HTML element conditionally.
  • ngClass - it dynamically set the CSS class to HTML element by evaluating the data binding expressions.
  • ngInit - used to assign default values while it is initialize.
  • Will used these directives regularly in future tutorials.
  • List of AngularJS built-in directives.

Two-way data binding

It is one of the main feature of AngularJS. It is automated synchronization of data between model and view. Its changes the view (front-end) when model (beck-end) is changes. Don't ask how is it working? It is dirty checks the previous values against the remembered values. It is fire the change event when value is changed. So far as good to use when $scope data is small in size. Otherwise it will degrade the performance.

<!DOCTYPE html>
<html ng-app>
  <!-- AngularJS CDN -->
  <script src=""></script>
    Name: <input type="text" name="Name" ng-model="name">
    <h3>Welcome {{name}}!</h3>
Enter Name:

Welcome {{name}}!