In AngularJS (version 1.x), two-way data binding is a feature that allows automatic synchronization of data between the model and the view. When the model changes, the view is updated, and when the view changes, the model is updated. This bidirectional data flow simplifies the process of keeping the user interface in sync with the underlying data.

Two-way data binding in AngularJS is achieved using the ng-model directive. This directive binds the value of an input element to a property in the controller’s scope. Any changes to the input element will automatically update the corresponding property in the controller’s scope, and vice versa.

Here’s a simple example to illustrate two-way data binding in AngularJS:

1. Set up the AngularJS App

Make sure to include the AngularJS library in your HTML file.

<!DOCTYPE html>
<html>
<head>
  <title>AngularJS Two-Way Data Binding</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>

<div ng-app="myApp" ng-controller="myController">
  <!-- Your HTML content goes here -->
</div>

<script>
  // Your AngularJS app and controller code go here
</script>

</body>
</html>

2. Create the AngularJS App and Controller

In the < script > section of your HTML file, define your AngularJS app and controller.

<script>
  var app = angular.module('myApp', []);

  app.controller('myController', function($scope) {
    // Initialize the model data
    $scope.message = "Hello, AngularJS!";
  });
</script>

3. Use ng-model for Two-Way Data Binding

In your HTML template, use the ng-model directive for two-way data binding. In this example, we’ll use an input field to demonstrate two-way data binding.

<div ng-app="myApp" ng-controller="myController">
  <h2>Two-Way Data Binding Example</h2>
  <input type="text" ng-model="message" />
  <p>{{ message }}</p>
</div>

In this example, the input field is bound to the message variable in the controller using ng-model=”message”. Any changes made in the input field will automatically update the message variable in the controller, and any changes to the message variable in the controller will be reflected in the input field and the paragraph (< p >) element due to the curly braces expression {{ message }}.

Now, whenever you type something in the input field, the text inside the paragraph element will be updated immediately with the same content, and vice versa. This is the essence of two way data binding in AngularJS.

Support On Demand!

                                         
Angular