AngularJS supports data binding. The view is updated whenever the model changes and vice versa. Thanks to AngularJS support for data binding we can avoid writing code in JavaScript that manipulates the DOM.

The behavior behind the DOM elements is modeled into controllers. AngularJS allows us to express this behavior in a clean readable form without the common JavaScript boilerplate.

The following code sample includes two files. The first file is the HTML file the web browser renders. The HTML file includes the views. The second file is a JavaScript file that includes the controllers.

The HTML file shows all phone numbers and includes a small form the user can use in order to add a new phone number to the address book.

<!doctype html>
<html ng-app>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js">
</script>
<script src="addressbook.js"></script>
</head>
<body>
<h2>Address Book</h2>
<div ng-controller="AddressBookController">
<table border=1>
<tr>
<th>first name</th>
<th>last name</th>
<th>number</th>
</tr>
<tr ng-repeat="contact in contacts">
<td>{{contact.firstName}}</td>
<td>{{contact.lastName}}</td>
<td>{{contact.number}}</td>
</tr>
</table>
<p></p>
<form ng-submit="addContact()">
<input type="text" ng-model="firstName" size="10"
placeholder="first name...">
<input type="text" ng-model="lastName" size="10"
placeholder="last name...">
<input type="text" ng-model="number" size="10"
placeholder="number...">
<input type="submit" value="add">
</form>
</div>
</body>
</html>

The addressbook.js file includes the definition for the AddressBookController function. The AddressBookController function is the controller binded with the main div element.

function AddressBookController($scope)
{
$scope.contacts =
[
{firstName:'dave', lastName:'jameson',
number:'0546655837'},
{firstName:'larisa', lastName:'dorfman',
number:'050923423'},
{firstName:'john', lastName:'oxford',
number:'0529346353'}
];
$scope.addContact = function()
{
if($scope.firstName && $scope.lastName && $scope.number)
{
$scope.contacts.push({firstName:$scope.firstName,
lastName:$scope.lastName, number:$scope.number});
$scope.firstName = '';
$scope.lastName = '';
$scope.number = '';
}
};
}

The following video clip shows the execution of this code sample, overviews the code and explains it.

Address Book Code Sample in AngularJS PRO

Leave a Reply

Your email address will not be published. Required fields are marked *