AngularJS Expressions: Array, Objects, $eval, Strings

โšก Smart Summary

AngularJS Expressions are code fragments placed inside double braces that bind data straight into a template. They evaluate numbers, strings, objects, and arrays, and the $eval function performs the same evaluation from inside a controller.

  • ๐Ÿงฉ Binding Syntax: Double braces render a value where the expression sits, giving the same result as the ng-bind directive.
  • ๐Ÿ”ข Supported Types: Numbers, strings, JavaScript objects accessed with dot notation, and arrays accessed by index all evaluate correctly.
  • ๐Ÿท๏ธ Inline Variables: The ng-init directive declares view-level variables that expressions can then read without a controller.
  • ๐Ÿ›ก๏ธ Forgiving Evaluation: Undefined properties yield undefined rather than throwing the ReferenceError plain JavaScript would raise.
  • ๐Ÿšซ Hard Limits: Loops, exceptions, function declarations, regular expressions, and the comma and void operators are unavailable.
  • โš™๏ธ Controller Evaluation: $scope.$eval evaluates an expression string in controller code and exposes the result to the view.
  • โš ๏ธ Support Status: AngularJS reached end of life on 31 December 2021 and receives no further security patches.

AngularJS Expressions

What is AngularJS Expressions?

Expressions are variables written inside double braces {{ }}. They are very commonly used within AngularJS, and appear throughout the earlier tutorials in this series.

โš ๏ธ Support notice: AngularJS reached end of life on 31 December 2021 and receives no further patches or security fixes. The syntax below remains accurate for maintaining existing AngularJS 1.x applications; new projects should use modern Angular, where interpolation braces still exist but ng-init and $eval do not.

Explain AngularJS Expressions with an example

AngularJS expressions are written inside double braces, as in {{expression}}.

Syntax: a simple example of an expression is {{5 + 6}}.

AngularJS expressions bind data to HTML in the same way as the ng-bind directive, and AngularJS displays the data exactly where the expression is placed.

In this example we show a simple addition of numbers as an expression.

AngularJS Expressions

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Event Registration</title>
</head>
<body>

    <script src="https://code.angularjs.org/1.8.3/angular.min.js"></script>

    <h1>Guru99 Global Event</h1>

    <div ng-app="">
        Addition : {{6+9}}
    </div>

</body>
</html>

Code Explanation:

  1. The ng-app directive is blank, which means no module supplies controllers, directives, or services to this page.
  2. A simple expression adds two numbers.

Output:

AngularJS Expressions

The addition of 9 and 6 takes place and the result, 15, is displayed.

AngularJS Numbers

Expressions work with numbers. This example multiplies two number variables, margin and profit, and displays the product.

AngularJS Numbers

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Event Registration</title>
</head>
<body>

    <script src="https://code.angularjs.org/1.8.3/angular.min.js"></script>

    <h1>Guru99 Global Event</h1>

    <div ng-app="" ng-init="margin=2;profit=200">
        Total profit margin

        {{margin*profit}}
    </div>

</body>
</html>

Code Explanation:

  1. The ng-init directive defines variables and their values in the view itself, much like local variables in any programming language. Here margin and profit are declared and assigned.
  2. The expression then multiplies those two local variables.

Output:

AngularJS Numbers

The multiplication of 2 and 200 takes place and the product, 400, is displayed.

AngularJS Strings

Expressions also work with strings. This example defines firstName and lastName and displays both.

AngularJS Strings

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Event Registration</title>
</head>
<body>

    <script src="https://code.angularjs.org/1.8.3/angular.min.js"></script>

    <h1>Guru99 Global Event</h1>

    <div ng-app="" ng-init="firstName='Guru';lastName='99'">
        First Name : {{firstName}}<br>
        Last Name : {{lastName}}
    </div>

</body>
</html>

Code Explanation:

  1. The ng-init directive defines firstName with the value โ€œGuruโ€ and lastName with the value โ€œ99โ€.
  2. The expressions {{firstName}} and {{lastName}} read those variables and display them in the view.

Output:

AngularJS Strings

Both values appear on screen.

AngularJS Objects

Expressions work with JavaScript objects, which consist of name-value pairs. The syntax of a JavaScript object looks like this:

var car = {type: "Ford", model: "Explorer", color: "White"};

This example defines a person object holding two key-value pairs, firstName and lastName.

AngularJS Objects

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Event Registration</title>
</head>
<body>

<script src="https://code.angularjs.org/1.8.3/angular.min.js"></script>

<h1>Guru99 Global Event</h1>

<div ng-app="" ng-init="person={firstName:'Guru',lastName:'99'}">
    First Name : {{person.firstName}}<br>
    Last Name : {{person.lastName}}
</div>

</body>
</html>

Code Explanation:

  1. The ng-init directive defines the object person with the key-value pairs firstName set to โ€œGuruโ€ and lastName set to โ€œ99โ€.
  2. The expressions {{person.firstName}} and {{person.lastName}} read those members. Because they belong to the object, dot notation is required to reach their values.

Output:

AngularJS Objects

The values of firstName and lastName appear on screen.

AngularJS Arrays

Expressions work with arrays. This example defines an array holding a student’s marks in three subjects and displays each value.

AngularJS Arrays

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Event Registration</title>
</head>
<body>

<script src="https://code.angularjs.org/1.8.3/angular.min.js"></script>

<h1>Guru99 Global Event</h1>

<div ng-app="" ng-init="marks=[1,15,19]">
    Student Marks<br>
    Subject1 : {{marks[0]}}<br>
    Subject2 : {{marks[1]}}<br>
    Subject3 : {{marks[2]}}
</div>

</body>
</html>

Code Explanation:

  1. The ng-init directive defines the array marks with the three values 1, 15, and 19.
  2. Expressions of the form marks[index] read each element.

Output:

AngularJS Arrays

The marks defined in the array are displayed.

AngularJS Expression capabilities and Limitations

Capabilities

  1. AngularJS expressions resemble JavaScript expressions and share much of the same power and flexibility.
  2. Where JavaScript raises a ReferenceError or TypeError on an undefined property, AngularJS evaluation is forgiving and yields undefined or null.
  3. Filters can be applied inside an expression to format data before it is displayed.
  4. The ternary operator is supported, so {{ isReady ? 'Yes' : 'No' }} is valid.

Limitations

  1. Loops and exception handling cannot be used inside an AngularJS expression. Conditional logic is limited to the ternary operator; if statements are not available.
  2. Functions cannot be declared in an expression, not even inside an ng-init directive.
  3. Regular expressions cannot be created inside an expression. A regular expression is a combination of symbols and characters used to match strings, such as .*\.txt$, and such literals are rejected.
  4. The comma operator (,) and the void operator are not permitted.

ng-bind vs Expression Braces: Which to Use

Double braces and the ng-bind directive produce the same rendered output, so the choice between them looks arbitrary. It is not. The two behave differently during the moment before AngularJS has finished loading, and that difference is visible to the person using the page.

Aspect {{ expression }} ng-bind
Written in Element content An element attribute
Before AngularJS loads Raw braces flash on screen Nothing is shown
Readability Higher โ€” the value sits inline Lower โ€” value is hidden in an attribute
Multiple values per element Yes No, one binding only
One-time binding Yes, with {{::value}} Yes, with ng-bind="::value"

The brief appearance of raw braces is known as the flash of uninterpolated content, and it happens because the browser renders the markup before AngularJS compiles it. Use ng-bind, or add the ng-cloak directive, for content visible above the fold. Braces remain the clearer and more readable choice everywhere else, particularly where several values appear inside one element.

Difference between expression and $eval

The $eval function evaluates expressions from inside the controller. Expressions evaluate in the view, whereas $eval evaluates in controller code.

This example uses $eval to add two numbers and place the result on the scope object so the view can display it.

Difference between expression and $eval

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Event Registration</title>
</head>
<body>

<script src="https://code.angularjs.org/1.8.3/angular.min.js"></script>

<div ng-app="sampleApp" ng-controller="AngularController">
    <h1>Guru99 Global Event</h1>
    {{value}}
</div>

<script>
    var sampleApp = angular.module('sampleApp', []);
    sampleApp.controller('AngularController', function($scope) {
        $scope.a = 1;
        $scope.b = 1;

        $scope.value = $scope.$eval('a+b');
    });
</script>

</body>
</html>

Code Explanation:

  1. Two scope variables, a and b, each hold the value 1.
  2. $scope.$eval evaluates their addition and assigns the result to the scope variable value.
  3. The view then displays value.

Output:

Difference between expression and $eval

The output shows the expression evaluated inside the controller, with the sum of the two scope variables sent to and displayed in the view.

FAQs

Prefixing an expression with two colons, as in {{::name}}, stops watching it once a value is resolved. This removes the watcher and lowers digest cost on pages with many static bindings.

$eval evaluates a string immediately against a scope. $parse returns a reusable function for repeated evaluation. $interpolate handles a whole template string containing braces rather than a single expression.

Mostly. AI tools keep the braces and rewrite filters as pipes, but ng-init variables have no Angular equivalent and must be moved into a component class by hand.

AI tools scan templates for function calls inside bindings, which re-run on every digest cycle, and suggest either caching the result on scope or switching to a one-time binding.

AngularJS evaluation is deliberately forgiving. A missing property yields undefined, which renders as an empty string, so a blank value usually means a typo in the property path rather than a runtime fault.

Summarize this post with: