Twoway Data Binding in AngularJS (original) (raw)
Last Updated : 11 Jul, 2022
In this article, we will see the Data Binding, along with understanding how the flow of code is from a Typescript file to an HTML file & vice-versa through their implementation.
In AngularJS, Data Binding refers to the synchronization between the model and view. In Two-way data binding, the flow of data is bidirectional i.e. when the data in the model changes, the changes are reflected in the view and when the data in the view changes it is reflected in the model. Two-way data binding is achieved by using the ng-model directive. The ng-model directive transfers data from the view to the model and from the model to the view.
Approach: The following approach will be implemented to achieve the Two-way Binding:
- Create a module
var app=angular.module('myApp',[])
- Add a controller to the module. Here you can write the logic for updating the model as the view changes.
app.controller('myCtrl',function($scope){})
- Specify the ng-model directive in the element
Example 1: This example shows how the ng-model directive can be used for two-way data binding.
HTML `
Two-way Data Binding in AngularJSGeeksforGeeks
Two-way Data Binding
Enter your name{{name}}
`
Explanation: In the above example, we have used the ng-model directive in the input element. When the user enters data in the input element it is reflected in the
tag where we have used an expression to display the value of 'name'. This is an example of two-way data binding as when we change the input control value the value of the variable 'name' also changes.
Output:
Example 2: In this example, we have created a registration form. The user fills in the details and clicks on the submit button. On clicking on the submit button the details filled by the user are displayed.
HTML `
Two-way Data Binding in AngularJSGeeksforGeeks
Two-way Binding
Registration form
Enter your nameEnter your age
Courses:
C++Java
Python
{{x.key}} | {{x.value}} |
`
Output: