Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Easy

AngularJS Expressions

Author Sagar Mishra
1 upvote
gp-icon
Basics of javascript
Free guided path
10 chapters
68+ problems
gp-badge
Earn badges and level up

Introduction

Hey Ninjas, Welcome back to the blog. In today's world, one of the most things that people give to each other is expression. It can be an expression of love, anger, or excitement. Similarly, the language AngularJS also offers different types of expressions. For example, Number Expression, String Expression, and many more.

AngularJS Expressions

This blog will discuss all the types of AngularJS Expressions in detail.

AngularJS Expressions

AngularJS logo

AngularJS Expressions are simple and minor JS code. It can be formatted in HTML (HyperText Markup Language) view using the interpolations {{double curly braces}}. The AngularJS directive acts as an attribute of the directive in the expressions. These expressions are resolved, and AngularJs returns the result precisely where the expression was written. 

AngularJS also allows us to write our expressions inside a directive using the ng-bind= "expression" syntax. AngularJs expressions can be string literals, operators, objects, variables, or arrays. These expressions are similar to Javascript but with a few enhancements. 

Syntax

AngularJs Expressions as Operators: 

<div> AngularJS expression Example 1: {{ 10 - 4 }} </div>


AngularJs Expressions as a Directive Attribute and String literals:

<button ng-click="expressionFunc"> {{AngularJS expression}} </button>


As we have discussed the syntax of these commonly used AngularJS Expressions, let's understand each of them in detail.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

AngularJS Number Expression

Well, it's simple. As the name suggests, AngularJs number expressions are expressions where we use the numbers and operators like (-,*,/,%, etc.) 

Let’s go through an example of number expressions in which we are going to add two variables.

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <title>Number Expression in AngularJs</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('expressionApp', []);
        app.controller('expressionController', function ($scope) {
            $scope.var1 = 12;
            $scope.var2 = 24;
        });
    </script>
</head>

<body ng-app="expressionApp">
    <form id="form1">
        <div ng-controller="expressionController">
            <div>
                <h1>Number Expression</h1>
            </div>
            <p>The First Number is : {{var1}}</p>
            <p>The Second Number is : {{var2}}</p>
            <p>The Result is : {{var1 + var2}}</p>
        </div>
    </form>
</body>

</html>


Output:

Number Expression output

In the above example, we are adding two variables, var1 and var2. We are also printing the sum as a result in the end.

AngularJS String Expressions

The strings expression in AngularJs is a code that performs the operations on string values as per the name. In the example, we will see how we can concatenate two strings. 

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <title>AngularJs String Expressions Example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('expressionApp', []);
        app.controller('expressionController', function ($scope) {
            $scope.var1 = 'Welcome to ';
            $scope.var2 = 'Coding Ninjas!';
        });
    </script>
</head>

<body ng-app="expressionApp">
    <form id="form1">
        <div ng-controller="expressionController">
            <div>
                <h2>AngularJS String Expression Example</h2>
            </div>
            <p>The First String is : {{var1}}</p>
            <p>The Second String is : {{var2}}</p>
            <p><b>Result is : </b>{{var1+" "+var2}}</p>
        </div>
    </form>
</body>

</html>


Output:

String Expressions output

In the above example, we are joining two strings, var1 and var2. We are also printing the concatenated string as a result in the end.

AngularJS Object Expressions

In this section, we will be learning about Object Expressions. Now, what are these expressions?

In AngularJs, the object expressions hold their properties and evaluate at the view when they are used. In the example, we will see how these expressions work. 

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <title>AngularJS Object Expressions Example</title>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

    <script type="text/javascript">
        var app = angular.module('expressionApp', []);
        app.controller('expressionController', function ($scope) {
            $scope.expression = {
                var1: 'I',
                var2: 'love',
                var3: 'Coding Ninjas!',
            };
        });
    </script>

</head>

<body ng-app="expressionApp">
    <form id="form1">
        <div ng-controller="expressionController">
            <h3>AngularJS JSON object contains key value pairs as</h3>
            variable 1 : {{expression.var1}} <br />
            variable 2 : {{expression.var2}} <br />
            variable 3 : {{expression.var3}}
    </form>
</body>

</html>


Output:

Object Expressions output

In the above example, we are taking an expression in which both the key and value pair are present. The ‘var1’, ‘var2’, and ‘var3’ are the keys and ‘I’, ‘love’, and ‘Coding Ninjas!’ are the values in the above example.

AngularJS Array Expressions

In the Array Expressions, the expressions store an array and use these array objects to evaluate the array expression in AngularJs. 

An example below explains how we can use Array Expressions in AngularJS. 

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <title>AngularJS Object Expressions Example</title>      
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
       
    <script type="text/javascript">
        var app = angular.module('expressionApp', []);
        app.controller('expressionController', function ($scope) {
            $scope.expression = {
                var1: 'I',
                var2: 'love',
                var3: 'Coding Ninjas!',
            };
        });
    </script>
</head>

<body ng-app="expressionApp">
       <form id="form1">
             <div ng-controller="expressionController">
                 <h3>AngularJS JSON object contains key value pairs as</h3>
                 variable 1 : {{expression.var1}} <br />
                 variable 2 : {{expression.var2}} <br />
                 variable 3 : {{expression.var3}}
       </form>
</body>

</html>


Output:

Array Expressions

We are printing a situation of a shopkeeper using the AngularJS Array Expressions. We have a pre-defined array that describes the price of fruits. Every statement tells the price at which the shopkeeper brought those fruits. 

Expression Capabilities and Limitations

As we have learned about the AngularJs expressions and the different types of expressions we have, there are a few capabilities and limitations of these expressions. Let's have a look at them. 

Capabilities of AngularJs Expressions:

  • These expressions are similar to JS expressions; both share capabilities. 
     
  • These expressions can contain literals, operators, and variables. 
     
  • These expressions support the use of filters. As if we use filters, we can format our data before it gets displayed.
     
  • We can contain the HTML code within these Angular expressions.
     

A few limitations of AngularJs Expressions:

  • These expressions cannot contain conditional statements, loops, exceptions, and even regular expressions. 
     
  • In AngularJs, we cannot declare a function, even within a <ng-init> directive.
     
  • These expressions cannot contain a comma or a void.
     
  • These expressions do not allow us to use the return keyword. 

One Time Binding

A one-time expression is one that begins with the symbol "::". The one-time expressions become stable after the first click. Also, it will not recalculate if the expression result is a non-undefined value.

The syntax of one-time binding is given below:

game="::gameName"
or,
ng-repeat="game in :: games"


You can use both syntaxes to use the one-time binding. Now, we will take a working example of One-time binding. The model is divided into three parts, "index.html", “protractor.js”, and “script.js”.

We are already familiar with the HTML and script files. The new term here is the protractor.js file. So, Protractor is a framework used for end-to-end testing of Angular and AngularJS apps. Protractor performs tests on the app while it is active in a real browser and interacts with it the same way a user would. 

index.html

<!doctype html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>AngularJS Expression</title>
    <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
    <script src="script.js"></script>
</head>

<body ng-app="CodingNinjasOneTimeBinding">
    <div ng-controller="CN_Event_Controller">
        <h2>One-Time Binding</h2>
        <button ng-click="clickMe($event)">Submit</button>
        <p id="cn-one-time-binding">One-Time Binding: {{::game}}</p>
        <p id="cn-normal-binding">Normal Binding: {{game}}</p>
    </div>
</body>

</html>


protractor.js

it('Binding is fixed after its value becomes stabilised',
    function () {
        var one_time_bind = element(by.id('cn-one-time-binding'));
        var normal_bind = element(by.id('cn-normal-binding'));

        expect(one_time_bind.getText()).toEqual('One-Time Binding:');
        expect(normal_bind.getText()).toEqual('Normal Binding:');
        element(by.buttonText('Submit')).click();

        expect(one_time_bind.getText()).toEqual('One-Time Binding: Cricket');
        expect(normal_bind.getText()).toEqual('Normal Binding: Cricket');
        element(by.buttonText('Submit')).click();

        expect(one_time_bind.getText()).toEqual('One-Time Binding: Cricket');
        expect(normal_bind.getText()).toEqual('Normal Binding: Football');
        element(by.buttonText('Submit')).click();

        expect(one_time_bind.getText()).toEqual('One-Time Binding: Cricket');
        expect(normal_bind.getText()).toEqual('Normal Binding: Hockey');
        element(by.buttonText('Submit')).click();

        expect(one_time_bind.getText()).toEqual('One-Time Binding: Cricket');
        expect(normal_bind.getText()).toEqual('Normal Binding: Chess');
        element(by.buttonText('Submit')).click();

        expect(one_time_bind.getText()).toEqual('One-Time Binding: Cricket');
        expect(normal_bind.getText()).toEqual('Normal Binding: Tennis');
        element(by.buttonText('Submit')).click();
    }
);


script.js

(
    function (angular) {
        'use strict';
        angular.module('CodingNinjasOneTimeBinding', []).
            controller('CN_Event_Controller', ['$scope',
                function ($scope) {
                    var cnt = 0;
                    var games = ['Cricket', 'Football', 'Hockey', 'Chess', 'Tennis'];
                    $scope.clickMe = function (clickEvent) {
                        $scope.game = games[cnt % games.length];
                        cnt++;
                    };
                }]);
    }
)
(window.angular);


Output 1:

Output 1 of One Time Binding

Output 2:

Output 2 of One Time Binding

Output 3:

Output 3 of One Time Binding

Explanation:

Let's understand the outputs in detail.

  • After running the code given above, you will see the screen shown in output 1. In output 1, there is a submit button and two lines saying one-time binding and normal binding. We are comparing both bindings at the same time.
     
  • After clicking on submit button for the first time, you will see a game name on both one-time binding and normal binding. The output screen is getting the names from the array we inserted in script.js. The interface will look like output 2.
     
  • After that, if you click on the submit button again, then the value of normal binding will change as per the given array. Here, the value of one-time binding will stay constant. Output 3 is the result after clicking the submit button the fifth time. It will print the first element of the array if you click the submit button again after finishing the last element of the array.

$eval and Expression

Now, we will understand the use of the $eval function. Expressions can be tested from the controller by using the $eval function. So, the controller function uses $eval, whereas the view uses expressions for evaluation.

Expressions in AngularJS are similar to JavaScript code typically used in bindings like "expression". To resolve AngularJS expressions, including "variable", AngularJS internally uses the $eval function.

Let's take a quick example.

<!DOCTYPE html>
<html>

<head>
    <meta chrset="UTF 8" />
    <title>AngularJS Expression</title>
</head>

<body>

    <script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>
    <script>
        var ninjaApp = angular.module('ninjaApp', []);
        ninjaApp.controller('AngularController', function ($scope) {
            $scope.var1 = 5;
            $scope.var2 = 1;
            $scope.output = $scope.$eval('var1-var2');
        });
    </script>
    <div ng-app="ninjaApp" ng-controller="AngularController">
        <h1>$eval and Expression</h1>
        <b>Result is: {{output}}</b>
    </div>
</body>

</html>


Output:

$eval and Expression output

Frequently Asked Questions

What are AngularJs Expressions?

AngularJs Expressions are more superficial, and minor Js code that can be formatted in HTML view using the interpolations.

What are the types of Angular expressions?

We have four types of AngularJS expressions: Strings Expressions, Number Expressions, Array Expressions, and Object Expressions.

What are a few limitations of AngularJS Expressions?

In AngularJs, we cannot declare a function, even within a <ng-init> directive. These expressions cannot contain conditional statements, loops, exceptions, and even regular expressions.

Why are expressions used in AngularJS?

AngularJS uses expressions to connect application data to HTML. AngularJS resolves the expressions and returns the resolved result to the original place where the expression was written. In AngularJS, expressions are written in double braces: {{expression}}.

What is the difference and similarity between Angular expression and JavaScript expression?

Expressions in Angular are tested against a one-time scope object. Expressions in JavaScript are tested against the global window. The similarity is both expressions can contain literals, variables and operators.

Conclusion

This article discusses the topic of AngularJS Expression. In detail, we have seen the definition of AngularJS Expression, their all types of expressions like numbers, strings, objects, and array expressions.

We hope this blog has helped you enhance your knowledge of AngularJS Expression. If you want to learn more, then check out our articles.

And many more on our platform Coding Ninjas Studio.
Check out this problem - Redundant Braces

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundles for placement preparations.

However, you may consider our paid courses to give your career an edge over others!

Happy Learning!

Previous article
OWASP Juice Shop
Next article
Pipe in Angular
Guided path
Free
gridgp-icon
Basics of javascript
10 chapters
68+ Problems
gp-badge
Earn badges and level up
Live masterclass