Episode 6 of 25

Expressions

Learn how to use expressions in AngularJS to output data in your templates.

Expressions are snippets of code inside double curly braces {{ }} that AngularJS evaluates and displays in the view.

Basic Expressions

<div ng-app="">
    <p>{{ 5 + 3 }}</p>          <!-- 8 -->
    <p>{{ "Hello" + " World" }}</p> <!-- Hello World -->
    <p>{{ 10 > 5 }}</p>         <!-- true -->
</div>

Expressions with Variables

<div ng-app="" ng-init="name='Alice'; price=9.99; qty=3">
    <p>Name: {{ name }}</p>
    <p>Total: {{ price * qty | currency }}</p>
    <p>Name length: {{ name.length }}</p>
    <p>Uppercase: {{ name.toUpperCase() }}</p>
</div>

Object Expressions

<div ng-init="user={firstName:'Alice', lastName:'Smith'}">
    <p>{{ user.firstName + ' ' + user.lastName }}</p>
</div>

Array Expressions

<div ng-init="colors=['Red','Green','Blue']">
    <p>First color: {{ colors[0] }}</p>
    <p>Total colors: {{ colors.length }}</p>
</div>

Expressions vs JavaScript

  • Expressions are evaluated against the $scope object, not the global window
  • Expressions cannot use conditionals (if statements), loops, or throw errors
  • Expressions are more forgivingundefined and null show as empty, not errors
  • Use ternary operators for simple conditionals: {{ active ? 'Yes' : 'No' }}