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 applicationng-controller— attaches a controller to a sectionng-model— binds form elements to model datang-repeat— loops over a collectionng-show/ng-hide— show/hide elementsng-if— conditionally add/remove elementsng-click— handle click eventsng-class— dynamically set CSS classesng-style— dynamically set inline stylesng-src— dynamic image sourceng-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>