Directives

A directive is an HTML attribute that AngularJS gives special meaning to — it's the mechanism that lets you write ng-repeat or ng-if directly in markup and have AngularJS turn it into real, dynamic behavior. You already met one, ng-model, in the last lesson; this one covers the other two you'll reach for constantly.

ng-repeat: rendering a list

ng-repeat clones the element it's on once per item in an array, giving each clone its own scope with that item available by name:

HTML fruit-list.html
<ul ng-app="" ng-init="fruits = ['Apple', 'Mango', 'Kiwi']">
  <li ng-repeat="fruit in fruits">{{ fruit }}</li>
</ul>
Rendered output
• Apple
• Mango
• Kiwi

ng-init is only used here to set up demo data inline — in a real app that array would come from a controller, covered in the next couple of lessons. ng-repeat="fruit in fruits" reads as "for each fruit in fruits," and produces one <li> per array element, each with its own fruit variable in scope.

ng-if: adding or removing an element entirely

ng-if removes an element from the page's DOM completely when its expression is false, and re-adds it when the expression becomes true — it doesn't just hide it visually:

HTML vip-badge.html
<div ng-app="" ng-init="points = 120">
  <p>Points: {{ points }}</p>
  <span ng-if="points > 100">🏆 VIP status unlocked</span>
</div>
Rendered output
Points: 120
🏆 VIP status unlocked

Because points > 100 is true, the <span> exists in the rendered DOM. If points were 90, that element wouldn't just be invisible — it would never be inserted into the page at all, and any directives inside it wouldn't run.

ng-if vs ng-show: AngularJS also has ng-show/ng-hide, which look similar but only toggle CSS (display: none) — the element stays in the DOM either way. Use ng-if when the content is expensive to render or shouldn't exist at all for some users (e.g. an admin-only panel); use ng-show for something that toggles frequently, since repeatedly adding and removing DOM nodes with ng-if is slower than just flipping a CSS property.