Two-way data binding in AngularJS is a feature that allows the synchronization of data between the model and the view. It means that any changes made to the model will automatically update the view, and any changes made to the view will update the model.
In AngularJS, two-way data binding is achieved using the ng-model directive. This directive binds the value of an input element to a property in the model. When the value in the input element changes, the corresponding property in the model is updated, and vice versa.
Here’s an example to illustrate two-way data binding in AngularJS:
HTML:
<input type="text" ng-model="name">
<p>Hello, {{name}}!</p>
JavaScript:
angular.module(‘myApp’, [])
.controller(‘myController’, function($scope) {
$scope.name = ‘John’;
});
In this example, the ng-model directive is used to bind the value of the input element to the "name" property in the model. Initially, the value of the "name" property is set to "John". When the user types in the input field, the value of the "name" property is automatically updated. Similarly, when the value of the "name" property is changed programmatically, the view is updated to reflect the new value.
Two-way data binding in AngularJS simplifies the process of keeping the model and view in sync, as developers don’t have to manually update the view or retrieve the updated values from the view. It helps in building responsive and interactive web applications.