# Friday, 25 March 2016

In the last article, we discussed Angular controllers. In this article, we will add code to a controller to do 2-way data binding.

The $scope object exists to hold stateful data. To use it, we add this object to the arguments of our controller, as shown in Listing 1.

app.controller("mainController", function($scope) {
...
} 

Because JavaScript is a dynamic language, we can create new properties on an object simply by assigning values to those properties. We can maintain state by adding properties to to the $scope object. For example, in Listing 2, we add the FirstName and LastName properties and assign the values "David" and "Giard", respectively.

app.controller("mainController", function($scope) {
  $scope.firstName = "David";
  $scope.lastName = "Giard"; 
}

Now that we have these values assigned, we can bind HTML elements to these properties in our web page, using the ng-bind attribute, as shown in Listing 3.

First: <input type="text" ng-model="firstName" />
<br /> 
 
Last: <input type="text" ng-model="lastName" /> 

We don't need to add the "$scope." prefix because it is implied. In this example, we bind these properties to 2 text boxes and the browser will display the property values.  But unlike the {{}} data binding syntax, this binding is 2-way. In other words, changing the values in the textbox will also change the value of the properties themselves. We can demonstrate this by adding a <div> element to the page to output the current value of these properties, as shown in Listing 3.

<div>Hello, {{$scope.FirstName}} {{$scope.LastName}}!</div> 

When the user modifies the text in the 2 textboxes, the text within the div immediately changes because both are bound to the same properties.

We can do the same with objects and their properties, as in the following example:

JavaScript:

$scope.customer = {
  firstName: "David",
  lastName: "Giard"
}; 

HTML:

First: <input type="text" ng-model="customer.firstName" />
<br /> 

        Last: <input type="text" ng-model="customer.lastName" />
By adding and manipulating properties of the $scope object and using the ng-model directive, we can implement 2-way data binding in our Angular applications.