Angular’s two-way data binding, my personal understanding is that if the data model is established through the model, then the data on the view will be correspondingly stored in the angular program. Data changes on the view will be synchronized to the model, and data changes on the model will also be synchronized to view.
The demo below:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>hello, AngularJS!</title> <script src="angular.js"></script> </head> <body> <div ng-app> <!-- ng-model指令将表单的value绑定到model的username变量--> <input ng-model="username" type="text" placeholder="请输入..."> <p>Hello, <strong>{{username}}</strong>!</p> </div> </body> </html>
Running result: After the program is run, enter text in the input box, and the following will change synchronously with the content of the input box. Isn’t it surprising! What used to require writing a large piece of js code (listening to the onchange event and assigning the value of the input to the strong element below) can now be completed with only one ng-model directive. Perfect!
Detailed case explanation:
1. The role of the ng-model instruction: establish a data model. There is a corresponding variable username in the model to store the value of the input element;
2. {{username}} is an expression, angular will automatically calculate the expression and replace it with the corresponding value.
3. When text is entered manually, the value of the input element changes and is automatically synchronized to the usename variable of the model. {{username}} reads the value of username from the model, so the content of the strong element below changes accordingly.
Synchronizing data is done by angular for us.
Thanks for reading, I hope it can help everyone, thank you for your support of this site!
For more AngularJS two-way data binding detailed explanation and simple examples, please pay attention to the PHP Chinese website!