AngularJS Directives

Updated on     Kisan Patel

A directive is really a new way to attaches special behavior to a DOM element. By default, a framework brings with it a basic set of directives such as iterate over an array, execute a custom behavior when an element is clicked, or even show a given element based on a conditional expression, and many others.

For example, ng-repeat, ng-show, ng-model, etc.

The ng-app directive is the first directive we need to understand because it defines the root of an AngularJS application. Applied to one of the elements, in general HTML or body, this directive is used to bootstrap the framework.

<!doctype html>
  <html ng-app>

Let’s take the example of the built-in ng-app and ng-model directive:

<!DOCTYPE html>
   <html ng-app>
       <title>AngularJS Simple app</title>
       <script src=""></script>
       <input ng-model="name" type="text" placeholder="Your name">
       <h1>Hello {{ name }}</h1>


Notice at the top we have ng-app. Any time you see ng- that is an Angular directive. The ng-app directive initializes an AngularJS application.

The ng-model directive binds the value of HTML input controls to application data.

If you want to use data-ng- instead of only ng- then you can do it. this would also work.

<div data-ng-app>
    <input data-ng-model="name" type="text" placeholder="Your name">
    <h1>Hello {{ name }}</h1>

<div ng-app>
        <h1>Total: {{ 3 + 4 }}</h1>

Expressions are really cool features. The expression {{ 3 + 4 }} is evaluated by Angular and the result 7 is rendered.

Adding the ng-app directive tells Angular to trick its magic. Note that removing ng-app will result in the browser rendering the expression as it is instead of evaluating it.

Iterating with ng-repeat Directive

<div ng-app>
     <div ng-init="names=['Kisan', 'Ravi', 'Devang', 'Jay', 'Ujas']">
            <h3>Looping with the ng-repeat Directive</h3>
              <li ng-repeat="name in names">{{ name }}</li>

Here, we have the ng-repeat, the ng-init: these are two directives. The ng-init directive initialize application data. Then the third is ng-repeat which will simply loop through all the names. Here, we have five names and so we would get five <li> with the name written out automatically.


Leave a Reply