Learn AngularJs Expressions With Examples

Read it in 12 Mins

Last updated on
07th Jun, 2022
Published
19th Sep, 2020
Views
9,398
Learn AngularJs Expressions With Examples

AngularJS is a dynamic and robust JavaScript-based MVW (Model View Whatever) Framework. One of the most popular open-source web application frameworks, Angular has been super-powered by Google since 2010. It is a toolset used for building the framework most suited to single page application development; but can also be utilized to work for other categories of web pages. Fully extensible, Angular works well with other web-based libraries. All its features can be modified and can even be replaced to suit your unique development workflow and web feature needs.   

Since AngularJS is a pure JavaScript framework, it can be added to an HTML page with a normal <script> tag with src attribute pointing to the source framework library, just like other JavaScript libraries.  

AngularJS extends HTML attributes using Directives.  It binds data to HTML using Expressions. 

AngularJS can be downloaded from. 

If you’re new to AngularJS, it is better to get introductory information from. This site provides the basic information required to start working with AngularJS. 

It has various features including MVC Architecture, Directives, Expressions, Controllers, Filters, HTML DOM, Modules, Views, AJAX, Scopes, Services, Dependency Injection, and Internationalization. We will deal with Expressions in the following section. 

Know more about angular cli.

Introduction  

Expressions 

In AngularJS, expressions are used to bind application data to HTML. AngularJS resolves the expression, and returns the result exactly where the expression is written. 

We will learn about each type of Expression in detail. 

The topics we will go through in this article are: 

  • Introduction to Expressions 
  • AngularJS Examples 
  • AngularJS using Numbers 
  • AngularJS using Strings 
  • AngularJS using Objects 
  • AngularJS using Arrays 
  • AngularJS Expression Capabilities and Limitations. 

Expressions in AngularJS 

Expressions are used to bind application data to html, and are written inside double braces in this manner: {{ expression}}. They behave in the same way as ng-bind directives. AngularJS application expressions are pure JavaScript expressions and output the data where they are used. They have the following qualities: 

  • Can be written inside double braces: {{ expression }}. 
  • Can also be written inside a directive: ng-bind="expression". 
  • AngularJS will resolve the expression, and return the result exactly where the expression is written. 
  • Much like JavaScript expressions, they can contain literals, operators, and variables. 

Example {{ 5 + 5 }} or {{ firstName + " " + lastName }} 

* Note: The ng-bind directive tells AngularJS to replace the content of an HTML element with the value of a given variable, or expression. If the value of the given variable or expression changes, the content of the specified HTML element will be changed as well. 

AngularJS Expressions and JavaScript expressions 

Let us compare Expressions in AngularJS and JavaScript. 

Similarity between AngularJS Expressions and JavaScript expressions: 

  • AngularJS expressions and JavaScript expressions can both contain literals, operators and variables. 

Differences between AngularJS Expressions and JavaScript expressions: 

  • ContextJavaScript expressions are evaluated against the global window. In AngularJS, expressions are evaluated against a scope object. 
    • AngularJS expressions do not have direct access to global variables like window, document or location. This restriction is intentional. It prevents accidental access to the global state – a common source of subtle bugs. 
    • Instead use services like $window and $location in functions on controllers, which are then called from expressions. Such services provide mockable access to globals. 
    • It is possible to access the context object using the identifier this and the locals object using the identifier $locals. 
    • AngularJS does not use JavaScript's eval() to evaluate expressions. Instead AngularJS's $parse service processes these expressions. 
  • Forgiving: In JavaScript, trying to evaluate undefined properties generates ReferenceError or TypeError. In AngularJS, expression evaluation is forgiving to undefined and null. 
    • In JavaScript, evaluating a.b.c throws an exception if a is not an object. While this makes sense for a general-purpose language, the expression evaluations are primarily used for data binding, which often look like this: {{a.b.c}} 
    • It makes more sense to show nothing than to throw an exception if a is undefined (perhaps we are waiting for the server response, and it will become defined soon). If expression evaluation wasn't forgiving, we'd have to write bindings that clutter the code, for example: {{((a||{}).b||{}).c}} 
    • Similarly, invoking a function a.b.c() on undefined or null simply returns undefined. 
  • FiltersYou can use filters within expressions to format data before displaying it. 
  • No Control Flow Statements: You cannot use the following in an AngularJS expression: conditionals, loops, or exceptions. 
    • Apart from the ternary operator (a ? b : c), you cannot write a control flow statement in an expression. The reason behind this is core to the AngularJS philosophy that application logic should be in controllers, not the views. If you need a real conditional, loop, or to throw from a view expression, delegate to a JavaScript method instead. 
  • No Function Declarations: You cannot declare functions in an AngularJS expression, even inside ng-init directive. 
  • No RegExp Creation with Literal Notation: You cannot create regular expressions in an AngularJS expression. An exception to this rule is ng-pattern which accepts valid RegExp. 
  • No Object Creation with New Operator: You cannot use new operator in an AngularJS expression. 
  • No Bitwise, Comma, And Void OperatorsYou cannot use Bitwise, or void operators in an AngularJS expression. 

Citation: (Docs from AngularJS) 

Thus, summarizing the JavaScript and AngularJS Expressions, we get the following main points: 

  • AngularJS expressions can be written inside HTML, while JavaScript expressions cannot. 
  • AngularJS expressions support filters, while JavaScript expressions do not. 
  • AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript expressions do. 
  • AngularJS expression cannot contain conditions, loops, exceptions or regular expressions e.g. if-else, ternary, for loop, while loop etc. 
  • AngularJS expression cannot declare functions. 
  • AngularJS expression cannot contain comma or void. 
  • AngularJS expression cannot contain return keyword. 

There are several categories in which Expressions operate. Some of the Expression Types are: 

  • Expressions Using numbers. Example: 
    • <p>Expense on Books : {{cost * quantity}} Rs</p> 
  • Expressions Using strings. Example: 
    • <p>Hello {{student.firstname + " " + student.lastname}}!</p> 
  • Expressions Using object. Example: 
    • <p>Roll No: {{student.rollno}}</p> 
  • Expressions Using array. Example: 
    • <p>Marks(Math): {{marks[3]}}</p> 

Let us go through each category in detail. 

Expression using Numbers 

Expression using numbers states that if any expression is using the number as variable or constant and the operators (like +, -, *, /, %, etc.) then those expressions are called number expressions.   

Say if we use the expression as: 

              <p>My first expression: {{ 5 + 5 }}</p> 

Then AngularJS will understand that this is a number expression. It will evaluate the expression and result in: 

             My first expression: 10 

We will understand more about the use of number expression in AngularJS with examples. 

Example:

Considering you have already downloaded the latest AngularJS file from (here we are using the minified version of AngularJS as angular.min.js). We can even use the AngularJS CDN for the same provided by Google: https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js

Example Using Curly Braces {{ }} for expressions: 

<!DOCTYPE html> 
<html> 
<head> 
<title>Number Expression of AngularJs</title> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script> 
<script> 
var app = angular.module('myApp', []) 
app.controller("myController", function ($scope) { 
$scope.expr1 = 10; 
$scope.expr2 = 20 
}); 
</script> 
</head> 
<body ng-app="myApp"> 
<form id="form1"> 
<div ng-controller="myController"> 
<div>Number Expression</div> 
<p>The Result of Addition is : {{expr1 + expr2}}</p> 
</div> 
</form> 
</body> 
</html> 

Now run the number expressions as an HTML file and check the output, which will look like this:

Learn AngularJs Expressions With Examples

Example Using ng-init and ng-bind for number expressions: 

<!DOCTYPE html> 
<html> 
<head> 
<title>Number Expression of AngularJs</title> 
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"> 
</script>  
</head> 
<body> 
<div ng-app="" ng-init="expr1=10; expr2=20"> 
<form id="form1">   
<p> 
The Result of Addition is :  
 <div ng-bind="expr1 + expr2"></div> 
</p>   
</form> 
</div> 
</body> 
</html> 

Now run the number expressions with ng-init and ng-bind as an HTML file and check the output, which will look like this: 

Learn AngularJs Expressions With Examples

Expression using String 

Expression using String iAngularJS is a unit of code to perform operations on string values like + operator for concatenation of String, or the angular.isString() function.   

* Note: The angular.isString() function in AngularJS is used to determine whether the parameter inside isString function is a string or not. It returns true if the reference is a string; and otherwise returns false.  

For example:

var obj1 = 123;  
var obj2 = "A String value";  
$scope.isString1 = angular.isString(obj1);  
$scope.isString2 = angular.isString(obj2); 
isString1 returns false while isString2 returns true. 

We will see how to use string expressions in detail in AngularJS with the following example: 

Example:

<!DOCTYPE html> 
<html> 
<head> 
<title>String Expressions of AngularJS</title> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script> 
<script> 
var app = angular.module('myApp', []) 
app.controller("myController", function ($scope) { 
$scope.expr1 = "Hello "; 
$scope.expr2 = "World"; 
$scope.expr3 = 100; 
var nexpr = $scope.expr3; 
var sexpr = $scope.expr1; 
$scope.isString1 = angular.isString(sexpr); 
$scope.isString2 = angular.isString(nexpr); 
}); 
</script> 
</head> 
<body ng-app="myApp"> 
<form id="form1"> 
<div ng-controller="myController"> 
<div>String Expression</div> 
<p> 
The Result of Concatenation of {{expr1}} and {{expr2}} is :  
{{expr1 + expr2}} 
</p> 
<p> 
The Result of angular.isString() for parameter  
{{expr1}} is : {{isString1}} 
</p> 
<p> 
The Result of angular.isString() for parameter  
{{expr3}} is : {{isString2}} 
</p> 
</div> 
</form> 
</body> 
</html> 

Now run the String expressions as an HTML file and check the output, which will look like this:

Learn AngularJs Expressions With Examples

Expression using Object 

The object expressions in AngularJS hold object properties in themAngularJS Objects and their fields are then evaluated at the view where they are used. For understanding AngularJS Objects, let’s go through the following section:  

Objects in AngularJS 

Before moving forth we need to understand objects in AngularJS.  AngularJS objects are the same as JavaScript objects, and consist of a name-value pair. 

AngularJs objects have two parts: the object name and the object definition. The object name is the name by which we identify the object. The object definition consists of field to value pair, which defines the complete object. 

For Example: Considering an object as AngularTraining with fields as Trainer, noOfStdnoOfHours, it can be defined as: 

$scope.AngularTraining = { 
TrainerMonica, 
noOfStd10, 
noOfHours24 
};  

To use an object, we use  a .(dot) operator. Eg: to get the name of the trainer in the above example, we identify by AngularTraining.Trainer which gives a value of Monica in this case. 

Note that $scope in AngularJS is a built-in object which basically binds the controller and the view. One can define member variables in the $scope within the controller which can later be accessed by the view. 

We will see how to use object expressions in detail in AngularJS with the following example: 

Example:

<!DOCTYPE html> 
<html> 
<head> 
<title>String Expressions of AngularJS</title> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script> 
<script> 
var app = angular.module('myApp', []) 
app.controller("myController", function ($scope) { 
$scope.AngularTraining = { 
Trainer: 'Monica', 
noOfStd: 10, 
noOfHours: 24 
};  
}); 
</script> 
</head> 
<body ng-app="myApp"> 
<form id="form1"> 
<div ng-controller="myController"> 
<div> 
<p> 
Pure JSON object contains key value pairs as Object Expression 
</p> 
</div> 
<p> 
The AngularTraining Object is: 
<br/> 
AngularTraining.Trainer{{ AngularTraining.Trainer}}  
<br/> 
AngularTraining.noOfStd{{ AngularTraining. noOfStd}}  
<br/> 
AngularTraining. noOfHours{{ AngularTraining. noOfHours}}  
 </p> 
</div> 
</form> 
</body> 
</html> 

Now run the Object expressions as an HTML file and check the output, which will look like this:

Learn AngularJs Expressions With Examples

Objects with ng-init definition: 

We can define the objects at ng-init as shown in the following example: 

<!DOCTYPE html> 
<html> 
<head> 
<title>String Expressions of AngularJS</title> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script> 
</head> 
<body> 
<form id="form1"> 
<div div ng-app="" ng-init = " AngularTraining = { Trainer'Monica',  noOfStd: 10, noOfHours: 24 }" > 
<div> 
<p> 
Pure JSON object contains key value pairs as Object Expression 
</p> 
</div> 
<p> 
The AngularTraining Object is: 
<br/> 
AngularTraining.Trainer{{ AngularTraining.Trainer}}  
<br/> 
AngularTraining.noOfStd{{ AngularTraining. noOfStd}}  
<br/> 
AngularTraining. noOfHours{{ AngularTraining. noOfHours}}  
 </p> 
</div> 
</form> 
</body> 
</html> 

Now run the Object expressions as an HTML file and check the output, which will look like this: 

Learn AngularJs Expressions With Examples

Expression using Array 

Arrays in AngularJS are the variables that hold a group of data just like any other programming language. The Expressions using Arrays evaluate these array objects and provide the output. 

Arrays in AngularJS 

An array is a group of values with a group name, with the values separated by commas.  An array is a special data type which can store multiple values of different data types sequentially using a special syntax. 

For example:

marks = [95, 52, 65, 98, 55, 35]; 

We will see how to use array expressions in AngularJS with the following example: 

Example:

<!DOCTYPE html> 
<html> 
<head> 
<title>String Expressions of AngularJS</title> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script> 
<script> 
var app = angular.module('myApp', []) 
app.controller("myController", function ($scope) { 
$scope.name = "Monica"; 
$scope.leave = [120]; 
}); 
</script> 
</head> 
<body ng-app="myApp"> 
<form id="form1"> 
<div ng-controller="myController"> 
<div> 
<p> 
Array Expression</p> 
</div> 
<p> 
The Leave Report for the first quarter for Employee: <br/> 
{{name}} is: 
<br/> 
January{{ leave[0] }}  
<br/> 
February{{ leave[1] }}   
<br/> 
March{{ leave[2] }}   
<br/> 
Total Leave for the first Quarter is: 
{{ leave[0] + leave[1] + leave[2] }} 
 </p> 
</div> 
</form> 
</body> 
</html> 

Now run the Array expressions as an HTML file and check the output, which will look like this:

Learn AngularJs Expressions With Examples

Defining Arrays with ng-init definition: 

We can define the arrays at ng-init as shown in the following example: 

<!DOCTYPE html> 
<html> 
<head> 
<title>String Expressions of AngularJS</title> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.0/angular.min.js"></script> 
</head> 
<body > 
<form id="form1"> 
<div div ng-app="" ng-init = " name = 'Monica'; leave = [120]; " > 
<div> 
<p> 
Array Expression</p> 
</div> 
<p> 
The Leave Report for the first quarter for Employee: <br/> 
{{name}} is: 
<br/> 
January{{ leave[0] }}  
<br/> 
February{{ leave[1] }}   
<br/> 
March{{ leave[2] }}   
<br/> 
Total Leave for the first Quarter is: 
{{ leave[0] + leave[1] + leave[2] }} 
 </p> 
</div> 
</form> 
</body> 
</html> 

Now run the Array expressions as an HTML file and check the output, which will look like this: 

Learn AngularJs Expressions With Examples

Complete Example

Summarizing the different types of AngularJS Expressions, we can understand that numbers and strings can be evaluated, while objects and arrays are converted to either numbers or strings first and then evaluated in AngularJS 

A complete example of AngularJS expression is: 

<!DOCTYPE html> 
<html>    
<head>       
<title>AngularJS Expressions</title>    
</head> 
   <body>       
<h1>Expression</h1> 
<div ng-app = "" ng-init = "quantity = 2; cost = 30; student = {firstname: 'Monica', lastname: 'Gupta', rollno: 34}; marks = [80, 90, 75, 73, 80] "> 
<p>Hello {{student.firstname + " " + student.lastname}}!</p> 
<p>Expense on Books : {{cost * quantity}} Rs</p> 
<p>Roll No: {{student.rollno}}</p> 
<p>Marks(Math): {{marks[3]}}</p> 
</div> 
<script src = "angular.min.js"></script> 
</body>  
</html> 

Now run the Expressions as an HTML file and check the output, which will look like this: 

Learn AngularJs Expressions With Examples

AngularJS Expression capabilities and Limitations 

AngularJS Expression capabilities 

  • Angular expressions have the same power and flexibility as JavaScript expressions.  
  • In JavaScript, when you try to evaluate undefined properties or objects or arrays, it generates a ReferenceError or TypeError. However, in AngularJS, expressions evaluation is forgiving and it generates an undefined or null value. 
  • In AngularJS expressions you can use filters within expressions to format data before displaying it. 

Angular JS Expression limitations 

  • Unlike JavaScript expressions, there is currently no availability to use conditionals, loops, or exceptions in an AngularJS expression 
  • You cannot declare functions in an AngularJS expression, not even inside ng-init directive. 
  • You cannot create regular expressions in an AngularJS expression. A regular expression is a combination of symbols and characters, which are used to search for strings such as : . * \ $ etc. Such expressions cannot be used within AngularJS expressions. 
  • Also you cannot use Bitwise, comma (,) or void operators in an AngularJS expression. 

Conclusion

AngularJS Expressions are used to evaluate values out of Numbers, Number variable, String variable, Objects or Arrays. 

AngularJS expressions are JavaScript-like code snippets that are mainly placed in interpolation bindings such as <span title="{attrBinding }}">{{ textBinding }}</span>. 

Some valid expressions are: 1+2, a+b, user.name, items[index] . 

Thus, we can say that Expressions are variables which were evaluated in the double braces {{ }}. It can be number Expressions, String Expressions, Object Expressions or Array Expressions. 


Note: Angular is a version upgrade to AngularJS. Therefore, Angular refers to AngularJS in this article.

Profile

Monica Gupta

Author

I am Monica Gupta with 19+ years of experience in the field of Training and Development. I have done over 500 Corporate Trainings. I am currently working as a freelancer for several years. My core area of work is Java, C++, Angular, PHP, Python, VBA.