I am a newbie trying to understand angular two way data binding. In the docs https://docs.angularjs.org/guide/databinding, it mentions "Any changes to the view are immediately reflected in the model, and any changes in the model are propagated to the view". So if there is an input box ( model ) and an expression ( view ) I can see that "and any changes in the model are propagated to the view" works, but I want to see an example of the opposite scenario, ie.,"Any changes to the view are immediately reflected in the model", and how could I demonstrate it my self. Any help would be highly appriciated. Thanks
what is two way data binding in angular
2.7k views Asked by user2243301 AtThere are 4 answers
Refer this working code JsFiddle
$watch will watch the variable (ng-model) for any changes in this case and invokes the function. Even without adding $watch, whatever you type in the input box gets updated in the backend automatically. $watch is one way to check if the model is updated properly.
On clicking Login button the latest model value will be present in the controller.
$scope.$watch('user.firstName',function(){
alert("Your name is changed to : "+$scope.user.firstName);
});
Two way data binding in angular:
It helps the user to pass the data from the component to view and from view to the component. so this will establish "bi-directional communication".
This can be achieved via [(ngModel)] and also known as 'banana-box syntax', refer it below for snippet to use:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `
Enter the value : <input [(ngModel)] ='val'>
<br>
Entered value is: {{val}}
`
})
export class AppComponent {
val: string = '';
}
Import FormsModule into app.module.ts to avoid Template parse error while using ngModel:
import { FormsModule } from "@angular/forms";
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [ AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
I Hope it's clear.
In this basic example of angularjs we are using a directive ng-model. It has two-way data binding ($scope --> view and view --> $scope).$scope is an object which maintains an array $$watchers for each object bound to it and each object in this array has a key 'last' which stores the last updated value in the model.
In this case "yourName" model is bound with $scope. So,angularjs internally looks up for change in this model using $watch and the digest cycle updated all the changes immediately to the view
You can also look up for the change in the model in your angular controller as
You'll see that if you change the view ie your inputbox,the model defined in ng-model is changed and this changed model reflects back to the view.