AngularJS Tutorial menu

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

html
<div ng-app="">
  <p>5 + 7 = {{ 5 + 7 }}</p>
  <p>{{ "Assalam " + "o Alaikum" }}</p>
  <p>{{ 1500 * 3 }}</p>
</div>
Output
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

html
<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>
Output
Price per kg: Rs 850
Quantity: 2 kg
Total: Rs 1700

Strings, Objects and Arrays

Example

html
<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>
Output
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

html
<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

html
<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.

FeatureAngularJS expressionJavaScript
Where it is writtenIn HTML, inside {{ }}In <script> or .js files
Math, strings, objectsYesYes
Ternary a ? b : cYesYes
Loops and if statementsNoYes
Declaring functionsNoYes
Filters with the pipe symbolYesNo
Errors on undefined valuesNo, shows emptyYes, 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

html
<div ng-app="" ng-init="marks=45">
  <p>Result: {{ marks >= 50 ? "Pass" : "Fail" }}</p>
</div>
Output
Result: Fail

Exercise

Exercise

What does {{ 20 * 3 }} show on an AngularJS page?

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