AngularJS Data Binding: Keeping Everything in Sync - FadiZahhar/AngularJs GitHub Wiki
The StartApp team is about to show their progress to their client.
The client says:
“I love that when I type, the preview updates right away! How does it work? And can we show live calculations too?”
Mike:
“That’s called data binding—it keeps the page and the data in sync. With AngularJS, it’s super easy!”
Sara:
“I can show both one-way and two-way data binding in just a few lines!”
-
Data binding means connecting data between your app (variables, models) and the UI (HTML), so that changes in one are reflected in the other.
-
In AngularJS, this is what makes everything update instantly—no need for manual JavaScript or refreshes.
Sara explains:
“With one-way binding, you display data from your model in the UI. If the data changes, the UI updates. But if the user changes the UI, the model doesn’t update.”
Example:
<div ng-app ng-init="greeting='Welcome!'">
<p>{{ greeting }}</p>
</div>
-
Change
greeting
in the code, and the UI shows the new value. -
But if you type in the UI, nothing happens to
greeting
.
Lina:
“Two-way binding is more magical. The UI and the model update each other. That’s what makes forms and live previews work!”
Example:
<div ng-app>
<input ng-model="name" placeholder="Enter your name">
<p>Hello, {{ name }}</p>
</div>
-
Type in the input, and the variable
name
updates. -
Change
name
elsewhere in your code, and the input updates too!
Mike:
“Let’s show a calculation that updates as you type.”
<div ng-app>
<input ng-model="a" placeholder="A">
<input ng-model="b" placeholder="B">
<p>Sum: {{ a*1 + b*1 }}</p>
</div>
(The *1
converts string inputs to numbers.)
Type | What Happens | How? | Example |
---|---|---|---|
One-way | Data flows from model to view only | {{ variable }} | {{ greeting }} |
Two-way | Data flows both ways (model <-> view) | ng-model + {{ }} | {{ x }} |
-
Sara: “No more writing
onchange
handlers just to show what a user typed.” -
Lina: “The UI and the data always match. It’s almost impossible to get them out of sync!”
-
Mike: “Makes forms, live previews, and interactive dashboards a breeze.”
Can you make a live dollar-to-euro converter using two-way binding?
Solution:
<div ng-app ng-init="rate=0.92">
<input ng-model="usd" placeholder="USD">
<p>EUR: {{ usd * rate }}</p>
</div>
-
One-way binding: Use
{{ variable }}
to display data—changes in code update the UI. -
Two-way binding: Use
ng-model
for form fields—UI and model update each other. -
Data binding is the reason AngularJS apps feel so modern and responsive!
Sara:
“Data binding saves us hours of work. Our forms and previews are always up to date!”
Mike:
“Ready for more advanced forms and validation using this pattern next!”
Try these examples live in the W3Schools AngularJS TryIt Editor.
Want to keep going with forms, validation, or advanced bindings? Or get all these chapters as a full document? Just ask!