Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
AngularJS Data Binding
3.
Data Binding and Directives
4.
Types of Data Binding
4.1.
One-Way Data Binding
4.1.1.
Interpolation Binding
4.1.2.
Property Binding
4.2.
Two-Way Data Binding
4.3.
Event Binding
5.
Pros of Data Binding
6.
Cons of Data Binding
7.
Frequently Asked Questions
7.1.
What is data binding in AngularJS?
7.2.
What do you mean by scopes in AngularJS? 
7.3.
Can we create reusable components in AngularJS?
7.4.
What do you mean by Model in MVC? 
7.5.
What do you mean by View in MVC? 
8.
Conclusion
Last Updated: Mar 27, 2024
Medium

AngularJS Data Binding

Author Sagar Mishra
1 upvote

Introduction

Hey Ninjas! Welcome back to the blog. You must have heard about AngularJS. AngularJS is a framework to make dynamic and high-quality web apps and games. Today we will take a step into one more exciting topic for a better understanding of workflow and concepts.

AngularJS data binding

In this blog, we will discuss AngularJS data binding in detail.

AngularJS Data Binding

AngularJS

The data binding is the synchronisation of data between two components: model and view. Data binding is used to connect the front end of any web app to the back end. You can also say that model is the app's source, and the view is the UI projection of the app. If you change the model, it will reflect in the view so fast that you will feel that the changes are done in real time.

Let's understand this with the help of a diagram.

model and view

The given diagram depicts the relation between the model and the view. If the user tries to change anything in the model, you can see the same changes in the view and vice versa.

Data Binding and Directives

The directive is something that makes binding in AngularJS possible. The directive which is used for binding data in AngularJS is ng-model. This directive binds the value of the text area, text field, or any other input field with the HTML element.

Let's see the code snippet performing data binding in AngularJS.

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    </head>
    <body>
        <div ng-app="">
            <h2>AngularJS Data Binding</h2>
            <p>Type your favourite game in the given area:</p>
            <p>Game Name: <input type="text" ng-model="game" /></p>
            <p>Your favourite game is: {{ game }}</p>
        </div>
    </body>
</html>


Output:

Data Binding and Directives output

In the example above, the expression inside the double curly braces is {{game}}. The expression {{game}} is bound with the ng-model directive (“game”). 

Types of Data Binding

The two types of data binding are mentioned below.

  1. One-Way data binding
     
  2. Two-Way data binding
     

Let's discuss both of them in detail.

One-Way Data Binding

One-Way Data Binding

As you can guess from the name and the diagram, this is a One-Way data binding and is unidirectional. If you make the changes in the model, then you must have to write a few lines of code by yourself to reflect the changes in the view also.

Let's take a quick example for better understanding.

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>AngularJs Data Binding</title>

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

        <script type="text/javascript">
            var app = angular.module("angularbindapp", []);

            app.controller("angularbindingCtrl", function ($scope) {
                $scope.name = "Hi, Welcome to Coding Ninjas!";
            });
        </script>
    </head>

    <body ng-app="angularbindapp">
        <div ng-controller="angularbindingCtrl">
            <h1>One-Way Binding Example</h1>
            <p>{{name}}</p>
        </div>
    </body>
</html>


Output:

One-Way Data Binding output

As you can see in the given output, you cannot change the data. To do so, you have to make the changes in the code.

Now, there are two types of one-way binding.

  1. Interpolation Binding
     
  2. Property Binding
     

Let's discuss these in brief.

Interpolation Binding

The interpolation technique is used to bind the value and its corresponding UI element. Interpolation binding works one way. When the field value is bound using interpolation changes, it is also updated on the page. It cannot change the value of the field. 

A Component class object is used as the data context for the component template. So the value we want to bound on the view must be assigned to a component class field.

Syntax: class="{{variable_name}}"

Let's try a working example. Here, we will use two types of files, one is HTML, and the other is a ts file. The ts file or TypeScript file is used to test an app component. Other unit tests are used in combination with this file. The command to run it is ng test.app.component in the Angular CLI.

app.component.html

<h2>{{ val }}</h2>
<h3>AngularJS Data Binding</h3>
<h3>Interpolation Example</h3>
<p><b>With Interpolation:</b> Difference between 8 and 4 is {{ 8 - 4 }}</p>
<p><b>Without Interpolation:</b> Difference between 8 and 4 is 8 - 4</p>


app.component.ts

import { Component } from '@angular/core';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
})
export class AppComponent {
    val: string = 'Welcome to Coding Ninjas';
}


Output:

Interpolation Binding output

As you can see in the output, the first line can print the difference between the numbers, but the second line cannot print the same. The reason behind this is the double curly braces we have used to print the first line. These double curly braces show the model's content to the view component.

Property Binding

Using this binding, we can bind values with the DOM properties of HTML elements. Property binding is also a one-way binding technique. Property bindings are calculated on every browser event, and every change made to the objects is applied to the properties.

DOM properties and HTML attributes of the HTML elements shouldn’t be confused. Every HTML element is considered a DOM object, and every attribute of the HTML element is represented as a DOM property.

Syntax:  [class]="variable_name"

Let's try an example:


app.component.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>AngularJS Data Binding</title>
    </head>
    <body>
        <h3>Welcome to Coding Ninjas</h3>
        <h3>Property Binding Example</h3>
        <div [ngClass]="myClass">Enter Text to Bind</div>
        <br />
        <div>
            <input [value]="myText" />
        </div>
    </body>
</html>


app.component.ts

import { Component } from '@angular/core';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
})
export class AppComponent {
    myText: string = 'Type Here';
    myClass: String = '';
}


Output 1:

Property Binding output 1

Output 2:

Property Binding output 2

The above code is binding ngClass to the myClass property using property binding. Output 1 will come when you first run your program. You can also fill in your input in the input text.

Two-Way Data Binding

The two-way data binding can change the model and view at the same time. When using two data binding in AngularJS, the data flow is not limited to one side. Since data can travel in both directions, two-way data binding uses a bidirectional method.

You can use the ng-model directive to implement this two-way data binding when the data in an input control changes, the ng-model directive in an HTML control will instantly update the value.

Two-Way Data Binding

In the above diagram, the template is an HTML code before compilation. It will create a view after the compilation process. Any changes made in view will directly reflect the model and vice versa.

Let's see a working example of two-way data binding.

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>AngularJs Data Binding</title>

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

        <script type="text/javascript">
            var app = angular.module("angularbindapp", []);

            app.controller("angularbindingCtrl", function ($scope) {
                $scope.input = "Coding Ninjas";
            });
        </script>
    </head>

    <body ng-app="angularbindapp">
        <h2>Two-Way Binding Example</h2>
        <div ng-controller="angularbindingCtrl">
            Enter something :
            <input type="text" ng-model="input" style="width: 250px" />

            <p>Output: {{input}}</p>
        </div>
    </body>
</html>


Output 1:

Two-Way Data Binding output 1

Output 2:

Two-Way Data Binding output 2

As you can see in the output above, we are writing text in the text area, which is reflected in the next line.

Event Binding

Event binding permits the browser to call a specific function each time an "event" takes place. The majority of events are related to user input, such as clicks, keystrokes, touches, and mouse movements. An example of an event binding to an event is $("#elem").

We will now see an example for good understanding.

app.component.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width= device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
        <h3>AngularJS Data Binding</h3>
        <p>Event Binding Example</p>
        
        <button class="btn btn-block"
            (click)="Clickme($event)">
            Click Me
        </button>
    </body>
</html>


app.component.ts

import { Component } from '@angular/core';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
})
export class AppComponent {
    title = 'Ninja Test';
    Clickme(event: any) {
        alert('Welcome to CodingNinjas!');
  }
}


Output 1:

Event Binding output

Output 2:

Event Binding output 2

Output 1 will come when you first run your program. And, on clicking the button "Click Me", you will see a pop-up with the message "Welcome to CodingNinjas!"

Pros of Data Binding

It's time to learn some pros of using AngularJS data binding. Let's have a look.

  • Apps based on data can be made rapidly and effectively.
     
  • You get the desired output with less coding.
     
  • You can take control of the data binding process by using events.
     
  • You can still quickly change the coding part even if your data is bound.

Cons of Data Binding

It is obvious if there are pros to something, there must also be some cons. So let's look at a few cons of AngularJS data binding.

  • Coding efficiency can only be increased by using a standard or unbound method.
     
  • Many programmers use conventional ways to increase the flexibility of data binding since it isn't entirely flexible.

Frequently Asked Questions

What is data binding in AngularJS?

Automatic data synchronisation between view and model components is known as data binding. 

What do you mean by scopes in AngularJS? 

Scopes are the model-referring objects. They act as glue between the view and the controller. 

Can we create reusable components in AngularJS?

Yes, we can create reusable components in AngularJS.

What do you mean by Model in MVC? 

The model component in MVC (Model View Controller) stores data with related logic transferred between the controller components or any affiliated business logic.

What do you mean by View in MVC? 

The view is responsible for displaying the complete or part of the data to the user.

Conclusion

This article discusses the topic of AngularJS Data Binding. In detail, we have seen the definition of AngularJS Data Binding and two types of data bindings. We also saw their advantages and disadvantages.

We hope this blog has helped you enhance your knowledge of AngularJS Data Binding. 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!

Live masterclass