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. 





Hello AngularJS

This article explains how to get started with AnglularJS and develop a simple application

Step 1: Include angular js file
Step 2: Include ng-app attribute (bootstrap our application.)
Step 3: Include ng-model attribute that need to be mapped to view.

Source:

<!DOCTYPE html>
<html ng-app>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

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

Hello {{ ename }}

<script type="text/javascript" src="../js/lib/angular.min.js"></script>
</body>

</html>


Whenever you type anything on the text box, the value gets bound to the model and in the code, we display whatever is present in the mode.

Note:
-          {{ ename }} is angularJS expressions where ename is model attribute. Ename is bound to the text box as well, so whenever the text box is changed, the model attribute value is changed and vice versa.
-          ng-model is an attribute used to bind the model with the view.

-          All the special html tags and attributes are called as “directives” in angularJS.