AngularJS Expression:
AngularJS expression is like JavaScript expression surrounded with braces - {{ expression }}. AngularJS evaluates the specified expression and binds the result data to HTML.
AngularJS expression can contain literals, operators and variables like JavaScript expression. For example, an expression {{2/2}}
will produce the result 1 and will be bound to HTML.
Example: Expression
<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body >
<h1>AngularJS Expression Demo:</h1>
<div ng-app>
2 + 2 = {{2 + 2}} <br />
2 - 2 = {{2 - 2}} <br />
2 * 2 = {{2 * 2}} <br />
2 / 2 = {{2 / 2}}
</div>
</body>
</html>
Result:
2 + 2 = 4
2 - 2 = 0
2 * 2 = 4
2 / 2 = 1
AngularJS expression is like JavaScript code expression except for the following differences:
- 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.
AngularJS expression contains literals of any data type.
Example: Expression
<html >
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body >
<h1>AngularJS Expression Demo:</h1>
<div ng-app>
{{"Hello World"}}<br />
{{100}}<br />
{{true}}<br />
{{10.2}}
</div>
</body>
</html>
Result:
Hello World
100
True
10.2
AngularJS expression can contain arithmetic operators which will produce the result based on the type of operands, similar to JavaScript:
Example: Expression
<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body >
<div ng-app>
{{"Hello" + " World"}}<br />
{{100 + 100 }}<br />
{{true + false}}<br />
{{10.2 + 10.2}}<br />
</div>
</body>
</html>
AngularJS expression can contain variables declared via ng-init directive. The ng-init directive is used to declare AngularJS application variables of any data type.
Example: Expression
<!DOCTYPE html>
<html >
<head>
<script src="~/Scripts/angular.js"></script>
</head>
<body >
<div ng-app ng-init="greet='Hello World!'; amount= 10000;rateOfInterest = 10.5; duration=10; myArr = [100, 200]; person = { firstName:'Steve', lastName :'Jobs'}">
{{ (amount * rateOfInterest * duration)/100 }}<br />
{{myArr[1]}} <br />
{{person.firstName + " " + person.lastName}}
</div>
</body>
</html>