Creating HTML forms in an Angular app
Having forms on your website is an easy way to get information from users. Angular’s two-way data binding makes standard HTML forms even more useful. Instead of using document.getElementbyID to get the data the user inputs, the form fields correspond to properties on our Angular controller. In this post, I will explain how to create a simple form for adding contacts to an Angular address book appplication.
The HTML below should look familiar if you have used a form, but I’ve added some Angular directives as well. The form is inside another div which is being controlled by FormController, defined with the ng-controller directive. The “as formCtrl” just adds an alias so we can refer to FormController as formCtrl if we want.
<div id=”ctrl-as-exmpl” ng-controller=”FormController as formCtrl”>
<form ng-submit = ‘addContact()’>
<input type = ‘text’ ng-model = ‘firstName’ size = ‘10’ placeholder = ‘firstname…’>
<input type = ‘text’ ng-model = ‘lastName’ size = ‘10’ placeholder = ‘lastname…’>
<input type = ‘text’ ng-model = ‘number’ size = ‘10’ placeholder = ‘number’>
<input type = ‘submit’ value = ‘add’>
</form>
</div>
The ng-submit directive specifies which method on the controller to call when the user submits the form. In this case, the method is addContact() Let’s take a look at the code for our controller to see this.
function FormController($scope) {
$scope.addressBook = [];
$scope.firstName = “”;
$scope.lastName = “”;
$scope.number = “”;$scope.addContact = function() {
if ($scope.firstName && $scope.lastName && $scope.number){
$scope.addressBook.push({firstName: $scope.firstName, lastName: $scope.lastName, number: $scope.number})
}
console.log($scope.addressBook);
}}
The ng-model directive specifies which property on the controller our input field is binding to.
<input type = ‘text’ ng-model = ‘firstName’ size = ‘10’ placeholder = ‘firstname…’>
This means that the input entered in this field on our form is bound to the ‘firstName’ property of our controller. If the user enters the name “Bob” our controller will have a firstName property with a value of “Bob”. The controller’s properties are initialized as empty strings.
The screen above shows our finished form. The user enters a first name, last name and number. These inputs then update the properties on our controller and the resulting object is pushed into our addressBook array which is logged on the console at the bottom of the screen.
This two-way binding makes forms very useful for Angular applications. Instead of simply logging the resulting data to the console, we could have saved that to a database or manipualted it in some other way. Angular makes creating and using HTML forms much easier than vanilla Javascript.