Episode 4 of 25
Two-Way Data Binding
Learn AngularJS two-way data binding — automatic sync between the model and the view.
Two-way data binding is AngularJS's most powerful feature. It automatically synchronises data between the model (JavaScript) and the view (HTML) in both directions.
How It Works
<div ng-app="" ng-init="name='World'">
<input type="text" ng-model="name">
<h1>Hello, {{ name }}!</h1>
</div>
Type in the input field and the heading updates instantly. That's two-way data binding!
The ng-model Directive
ng-model binds a form element to a model variable:
<div ng-app="" ng-init="user={name:'Alice', age:25}">
<p>Name: <input type="text" ng-model="user.name"></p>
<p>Age: <input type="number" ng-model="user.age"></p>
<h2>{{ user.name }} is {{ user.age }} years old</h2>
</div>
One-Way vs Two-Way
- One-way — data flows from model to view only (like
{{ expression }}) - Two-way — data flows both ways (model ↔ view via
ng-model)
ng-bind Alternative
<!-- Double curly braces -->
<p>{{ message }}</p>
<!-- ng-bind (prevents flash of {{ }} on slow loads) -->
<p ng-bind="message"></p>
Why Is This Powerful?
Without AngularJS, you'd need to manually write JavaScript to listen for input changes, update variables, and re-render the DOM. AngularJS does all of this automatically.