Using Expressions

Using expressions is the simplest way to represent data from the scope in an AngularJS view. Expressions are encapsulated blocks of code inside brackets: {{expression}}. The AngularJS compiler compiles an expression into HTML elements so that the results of the expression are displayed. For example, look at the following expressions:

{{1+5}}
{{'One' + 'Two'}}

Based on those expressions, the web page displays these values:

6
OneTwo

Expressions are bound to the data model, which provides two huge benefits. First, you can use the property names and functions that are defined in the scope inside your expressions. Second, because the expressions are bound to the scope, when data in the scope changes, so do the expressions. For example, say that the scope contains the following values:

$scope.name='Brad';
$scope.score=95;

You can directly reference the name and score values in the template expressions as shown here:

Name: {{name}}
Score: {{score}}
Adjusted: {{score+5}}

AngularJS expressions are similar to JavaScript expressions in several ways, but they differ in these ways:

Attribute evaluation: Property names are evaluated against the scope model instead of against the global JavaScript namespace.

More forgiving: Expressions do not throw exceptions when they encounter undefined or null variable types; instead, they treat these as having no value.

No flow control: Expressions do not allow JavaScript conditionals or loops. Also, you cannot throw an error inside an expression.

AngularJS evaluates the strings used to define the value of directives as expressions. This enables you to include expression-type syntax within a definition. For example, when you set the value of the ng-click directive in the template, you specify an expression. Inside that expression, you can reference scope variable and use other expression syntax, as shown here:

<span ng-click="scopeFunction()"></span>
<span ng-click="scopeFunction(scopeVariable, 'stringParameter')"></span>
<span ng-click="scopeFunction(5*scopeVariable)"></span>

Since the AngularJS template expressions have access to the scope, you can also make changes to the scope inside the AngularJS expression. For example, the following ng-click directive changes the value of msg inside the scope model:

<span ng-click="msg='clicked'"></span>

The following sections take you through some examples of utilizing the expression capability in AngularJS.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset