Episode 5 of 25

Introduction to Directives

Learn what AngularJS directives are and how they extend HTML.

Directives are special HTML attributes that tell AngularJS to do something to the DOM. They are the building blocks of every AngularJS application.

What Are Directives?

Directives are HTML attributes that start with ng-. They add behaviour to HTML elements:

<div ng-app="myApp">       <!-- Initializes the app -->
    <div ng-controller="MainCtrl"> <!-- Attaches a controller -->
        <input ng-model="name">    <!-- Two-way binding -->
        <p ng-if="name">Hello!</p> <!-- Conditional display -->
    </div>
</div>

Common Built-in Directives

  • ng-app — defines the root of the application
  • ng-controller — attaches a controller to a section
  • ng-model — binds form elements to model data
  • ng-repeat — loops over a collection
  • ng-show / ng-hide — show/hide elements
  • ng-if — conditionally add/remove elements
  • ng-click — handle click events
  • ng-class — dynamically set CSS classes
  • ng-style — dynamically set inline styles
  • ng-src — dynamic image source
  • ng-init — set initial values

ng-init

<div ng-init="name='Alice'; age=25">
    <p>Name: {{ name }}</p>
    <p>Age: {{ age }}</p>
</div>

ng-if vs ng-show

<!-- ng-if: removes/adds the element from the DOM -->
<p ng-if="showMessage">Visible!</p>

<!-- ng-show: hides with CSS (display:none), element stays in DOM -->
<p ng-show="showMessage">Visible!</p>