What is AngularJS Expression
In AngularJS, expressions are used to bind application data to HTML. AngularJS resolves the expression, and return the result exactly where the expression is written.
Expressions are written inside double braces {{expression}}.They can also be written inside a directive:
ng-bind="expression".
AnularJS expressions are very similar to JavaScript expressions. They can contain literals, operators, and variables. For example:
{{ 5 + 5 }} or {{ firstName + " " + lastName }}
Example Using Expression
Using numbers
Expense on Books : {{cost * quantity}} Rs
Using Strings
Hello {{student.firstname + " " + student.lastname}}!
Using Object
Roll No: {{student.rollno}}
Using Array
Marks(Math): {{marks[3]}}
AngularJS Numbers
<html >
<head>
<title>AngularJS Expression</title>
</head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
<body>
<div ng-app = "" ng-init="quantity=5;cost=5">
<p>Total in Rupees: {{ quantity * cost }}</p>
</div>
</body>
</html>
AngularJS String
<html >
<head>
<title>AngularJS Expression</title>
</head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
<body>
<div ng-app = "" ng-init="firstName='riya';lastName='mehta'">
<p>My full name is: {{firstName + " " + lastName }}</p>
</div>
</body>
</html>
AngularJS Object
<html >
<head>
<title>AngularJS Expression</title>
</head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
<body>
<div ng-app = "" ng-init="person={firstName:'Jiya',lastName:'Kapoor'}">
<p>My name is {{ person.firstName }}</p>
</div>
</body>
</html>
AngularJS Arrays
<html >
<head>
<title>AngularJS Expression</title>
</head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
<body>
<div ng-app = "" ng-init="points=[1,15,19,2,40]">
<p>The first result is {{ points[0] }}</p>
</div>
</body>
</html>
AngularJS Expressions vs. JavaScript Expressions
- Like JavaScript expressions, AngularJS expressions can contain literals, operators, and variables.
- Unlike JavaScript expressions, AngularJS expressions can be written inside HTML.
- AngularJS expressions support filters, while JavaScript expressions do not.
- AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript expressions do.