AngularJS Tutorial menu

AngularJS Directives

Directives are special HTML attributes that start with ng-. They give HTML new behaviour.

The Main Directives

DirectiveWhat it does
ng-appStarts the AngularJS application
ng-modelConnects an input to a variable (two-way binding)
ng-bindShows a value inside an element
ng-initSets starting values
ng-repeatRepeats an element for each item in a list
ng-show / ng-hideShows or hides an element with CSS
ng-ifAdds or removes an element
ng-classAdds CSS classes based on conditions
ng-src / ng-hrefSets image and link addresses with expressions
ng-clickRuns code on click (see the Events lesson)

You may also see the form data-ng-app or data-ng-model. The data- prefix makes the HTML valid and works the same way.

ng-model

ng-model connects form fields to data. The value is updated in both directions.

Example

html
<div ng-app="">
  <p>Your city: <input ng-model="city"></p>
  <p>You live in {{ city }}.</p>
  <p>Agree to terms: <input type="checkbox" ng-model="agreed"></p>
  <p>Agreed: {{ agreed }}</p>
</div>
Output
(typing "Hyderabad" and ticking the box)
You live in Hyderabad.
Agreed: true

ng-repeat

ng-repeat repeats an element once for each item in an array.

Example

html
<div ng-app="" ng-init="subjects=['Maths', 'Physics', 'Computer Science', 'English']">
  <ul>
    <li ng-repeat="s in subjects">{{ $index + 1 }}. {{ s }}</li>
  </ul>
</div>
Output
1. Maths
2. Physics
3. Computer Science
4. English

It also works with arrays of objects:

Example

html
<div ng-app="" ng-init="products=[
    {name:'Pen', price:40},
    {name:'Notebook', price:180},
    {name:'Geometry Box', price:350}]">
  <table>
    <tr ng-repeat="p in products">
      <td>{{ p.name }}</td>
      <td>Rs {{ p.price }}</td>
    </tr>
  </table>
</div>
Output
Pen            Rs 40
Notebook       Rs 180
Geometry Box   Rs 350

Inside ng-repeat you can use $index, $first, $last, $even and $odd.

If an array can contain the same value twice, AngularJS shows an error about duplicates. Add track by $index (or better, a unique id): ng-repeat="s in subjects track by $index".

ng-show, ng-hide and ng-if

Example

html
<div ng-app="">
  <label><input type="checkbox" ng-model="showDetails"> Show details</label>

  <p ng-show="showDetails">Classes: Monday to Friday, 4 pm to 6 pm.</p>
  <p ng-hide="showDetails">Tick the box to see class timings.</p>
  <p ng-if="showDetails">This paragraph is added and removed by ng-if.</p>
</div>

The difference matters for performance and bugs:

  • ng-show and ng-hide keep the element in the page and toggle display: none
  • ng-if removes the element completely and creates it again when needed. It also creates a new child scope

ng-class

ng-class takes an object. Each class is added when its condition is true:

Example

html
<style>
  .paid { color: green; }
  .late { color: red; font-weight: bold; }
</style>

<div ng-app="" ng-init="status='late'">
  <p ng-class="{ paid: status == 'paid', late: status == 'late' }">Fee status: {{ status }}</p>
</div>

ng-src and ng-href

Never write src="{{ photo }}". The browser tries to load the literal text {{ photo }} before AngularJS runs. Use ng-src instead:

Example

html
<img ng-src="{{ photoUrl }}" alt="Student photo">
<a ng-href="{{ profileLink }}">Open profile</a>

Custom Directives

Old projects often contain their own directives, created with module.directive():

Example

js
app.directive("shopBanner", function () {
  return {
    restrict: "E",
    template: "<h2>Welcome to Karachi Book Centre</h2>"
  };
});

Example

html
<shop-banner></shop-banner>

Note that a directive named shopBanner in JavaScript is written shop-banner in HTML.

Exercise

Exercise

Which directive repeats an element for each item in an array?

Learn AngularJS with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp