Thursday, June 19, 2014

2-way Data binding


A model is a javascript object (data holder) which holds information for the view to render and controller to process. To define a model, just assign them to $scope scope. 

Example:
$scope.ename="Deiveehan Nallazhagappan";

The values can be single value, any valid javascript object or even an array. 

<body>

A controller is a AngularJS javascript object which is tied to the view. Its main responsibility is to provide default values to the model and supplement them with more UI specific functionalities. 

<div ng-controller="Student">
Enter your name : <input type="text" ng-model="ename">
<br>

Hello {{ ename }}
</div>


<script type="text/javascript" src="../js/lib/angular.min.js"></script>
<script type="text/javascript">
var Student = function($scope) {
       $scope.ename="Deiveehan Nallazhagappan";
}

</script>

Note:
--       ng-controller is an attribute used to map a controller to a view.
-          The controller object is available only to that view.
-          $scope object in the controller is a special object which contains custom models. In this case, the ename attribute is available in the scope object which is available only to that div having the controller.

In the above code, the ename attribute is modified when the page loads. This is done using the sentence

$scope.ename="Deiveehan Nallazhagappan";

And the data is updated both in the label and the text box. And whenever you modify the data in the textbox, the data is updated in the model.
This is called 2-way data binding and is a very important feature of AngularJS. 





No comments:

Post a Comment