Home > Web Front-end > JS Tutorial > AngularJS two-way data binding detailed simple example

AngularJS two-way data binding detailed simple example

高洛峰
Release: 2016-12-24 10:30:18
Original
1195 people have browsed it

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>
Copy after login

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!

AngularJS 双向数据绑定

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!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template