AngularJS Expressions
AngularJS expressions show data on the page. They are written inside double curly braces.
Writing Expressions
An expression goes inside {{ }}. AngularJS works out its value and puts the result in the page.
Example
<div ng-app="">
<p>5 + 7 = {{ 5 + 7 }}</p>
<p>{{ "Assalam " + "o Alaikum" }}</p>
<p>{{ 1500 * 3 }}</p>
</div>5 + 7 = 12 Assalam o Alaikum 4500
If AngularJS is not loaded, or there is a script error, the page shows the raw text {{ 5 + 7 }}. This is a quick way to notice that something is broken.
Expressions with Variables
Expressions can use variables from ng-model, ng-init or a controller:
Example
<div ng-app="" ng-init="price=850; qty=2">
<p>Price per kg: Rs {{ price }}</p>
<p>Quantity: {{ qty }} kg</p>
<p>Total: Rs {{ price * qty }}</p>
</div>Price per kg: Rs 850 Quantity: 2 kg Total: Rs 1700
Strings, Objects and Arrays
Example
<div ng-app=""
ng-init="student={name:'Ali', city:'Karachi'}; marks=[78, 91, 64]">
<p>Name: {{ student.name }}</p>
<p>City: {{ student.city }}</p>
<p>Second mark: {{ marks[1] }}</p>
<p>Name length: {{ student.name.length }}</p>
</div>Name: Ali City: Karachi Second mark: 91 Name length: 3
ng-bind: Another Way to Show Data
ng-bind puts a value into an element, just like {{ }}:
Example
<p>Total: <span ng-bind="price * qty"></span></p>The advantage is that the user never sees raw {{ }} text while the page is loading.
Hiding Raw Braces with ng-cloak
Another fix for the "flash of braces" problem is ng-cloak:
Example
<style>
[ng-cloak] { display: none !important; }
</style>
<div ng-app="" ng-cloak>
<p>{{ "This text appears only after AngularJS is ready" }}</p>
</div>Expressions vs JavaScript
AngularJS expressions look like JavaScript, but they are more limited.
| Feature | AngularJS expression | JavaScript |
|---|---|---|
| Where it is written | In HTML, inside {{ }} | In <script> or .js files |
| Math, strings, objects | Yes | Yes |
Ternary a ? b : c | Yes | Yes |
Loops and if statements | No | Yes |
| Declaring functions | No | Yes |
| Filters with the pipe symbol | Yes | No |
| Errors on undefined values | No, shows empty | Yes, may throw an error |
The last row is important: if a variable does not exist, {{ missing.name }} simply shows nothing instead of crashing.
Keep expressions short. If you need real logic, write a function in a controller and call it, for example {{ getTotal() }}.
The Ternary Operator
Example
<div ng-app="" ng-init="marks=45">
<p>Result: {{ marks >= 50 ? "Pass" : "Fail" }}</p>
</div>Result: Fail
Exercise
Exercise
What does {{ 20 * 3 }} show on an AngularJS page?
