Let's extend the preceding example to illustrate two-way data binding:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.17/angular.min.js"></script> <title>AngularJS - Two way data binding</title> </head> <body> <div ng-app> <div> <h2 style="color:blue;">One way data binding? Cool!</h2> <label>Name:</label> <input type="text" ng-model="yourName" placeholder="Enter a name here"> <h3>Hello {{yourName}}!</h3> </div> <hr /> <div> <h2 style="color:green;">Two way data binding? Great!</h2> <textarea type="text" ng-model="newName" placeholder="Enter some text to change the value of the underlying model"></textarea> <button ng-click="yourName = newName"> Change the underlying model's value </button> </div> </div> </body> </html>
(two-way-data-binding.html
)
We've made very few changes to our preceding Hello World example. We introduced a
<textarea>
element and bound it to a new model variable callednewName
.We added a
<button>
element, and we are handling its clicked event (using thengClick
directive). Inside the click event, we just assigned the value of thenewName
new model to our old variableyourName
.As soon as you enter some text in the
textarea
value and click on the Change the underlying model's value button, thetextarea
value is reflected in the Name textbox and the Hello label.This shows two-way data binding in action. The UI control reflects the value of the underlying model and vice versa.