Great, so far we have seen binding data with views using double braces {{}}, ng-model and onClick assigning it to $scope variable which is binded in the html. This example is going to illustrate the two way binding. To better illustrate that how about we just have a text input and any value entered in the text input should be auto populated on top of the text input.
<html> <head> <script src="js/lib/angular.min.js"></script> <script src="js/controllers/mainController.js"></script> </head> <body ng-app="appViewer"> <div ng-controller="mainController"> <div>Two Way Binding Example</div> <div> </div> <input type="text" placeholder="Type here"> </div> </body> </html>
So in the above code, we have created a input text box and on top of it we have created a div with nothing. So if you run this you will see a text input and when you type nothing will happen. So lets try to add some magic here.
<div> {{title}}</div> <input type="text" ng-model="title" placeholder="Type here">
So in the above code, I have just added a ng-model directive and placed a string called title and bind the same title string inside the double braces on top of the text input. Now we are all set, if you run the application and type anything inside the text input it automatically appears on the top div.
How this works?
Please note for the above example we have not added a single line of code in any of the javascript files or the controllers, everything happened within the HTML mark up itself. Its interesting to know that any variable created inside the {{var}} or equated to ng-model will be magically created inside angular $scope bound to that controller. So in our example, the moment angular sees “title” string inside the {{title}} it automatically creates title object inside its $scope and since the same string is attached to ng-bind directive which in turn is attached to the text input. Now any change in the text input will update the $scope.title, which affects the view because the “title” string is bound inside the double braces on a div inside the same controller. Angular in general watches the changes in object model by running a digest cycle and update the modified object now and then in its respective scopes. We will see about $digest cycle in the future chapters.
Leave a Reply