Expressions - AngularJS

AngularJS expressions are used for display data from your Model to View.

You can write expressions in double curly braces {{ expression }}.

It is like one way binding from your Model to View and works just like ng-bind attribute.

AngularJS expressions output the data where it is written. You can write expression with any numbers, strings, objects and arrays.


AngularJS Expression examples

<!DOCTYPE html>
<html>
	<head>
		<title>First AngularJS App</title>
	</head>
<body>
	<div ng-app ng-init="firstName='James';lastName='Landridge';empObj={ prop1: 'test1' };arrObj=[42,32,91];">
		<p><b>Numeric Expression</b>: 5 + 6 = {{ 5 + 6 }}<p>
		<p><b>String Expression</b>: {{ firstName + " " + lastName}}</p>
		<p><b>Object Expression</b>: Object property value is {{ empObj.prop1 }}</p>
		<p><b>Array Expression</b>: Array first index value is {{ arrObj[0] }}</p>
	</div>
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
</body>
</html>

The ng-init directive is used for evaluating the expression.

In line 8, we initialize the string, object and array variables.

In line 9, we use expression for summing the values.

In line 10, we use expression for concatenating the string variables.

In line 11, we use expression for showing property 'prop1' of empObj variable.

In line 12, we use expression for showing first index value of arrObj variable.


Expression One-time binding

Expressions are also supports one-time binding which is not supported in ng-bind.

In one-time binding, expression is evaluated only once after that any changes in expressions variable values are not evaluated and displayed.

You can use double colon (::) to denote one-time binding.

<!DOCTYPE html>
<html>
	<head>
		<title>First AngularJS App</title>
	</head>
<body>
	<div ng-app ng-init="firstName='James';">
		<p><input type="textbox" ng-model="firstName" />
			{{ ::firstName }}
		</p>
	</div>
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
</body>
</html>

In the above example, I have initialized the firstName javascript variable with 'James' string. firstName variable is also bind to textbox but textbox changes will not shown in the {{ ::firstName }} expression.

Expression_OneTimeBinding

In the above screenshot, expression is evaluated as 'James'. If you type anything in textbox it will not reflect in the expression because of one-time binding.

Join our newsletter and get an occasional email with a technology and DotNetPattern.com news update.