fastread homefastrread library fastread menu

AngularJS : Form Handling Introduction

Tutorial by:Sumit Chauhan      Date: 2016-08-12 00:23:02

❰ Previous Next ❱

AngularJS has some features for binding data of HTML form input fields to the model object ($scope). These features makes it easier to work with forms.

You bind an input field to a model property using the ng-model directive like this:

<input type="text" id="firstName" ng-model="myForm.firstName">

This binding is two-way, meaning if the $scope.myForm.firstName has a value set inside the corresponding controller function, the input field will start with that value. Additionally, once the user types something into the text field, that value will be copied from the text field into the $scope.myForm.firstName property.

Here is a full AngularJS form example you can play with:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>

<body ng-app="myapp">

<div ng-controller="MyController" >
    <form>
        <input type="text" name="firstName" ng-model="myForm.firstName"> First name <br/>
        <input type="text" name="lastName"  ng-model="myForm.lastName"> Last name <br/>
    </form>

    <div>
        {{myForm.firstName}} {{myForm.lastName}}
    </div>
</div>

<script>
    angular.module("myapp", [])
            .controller("MyController", function($scope) {
                $scope.myForm = {};
                $scope.myForm.firstName = "Jakob";
                $scope.myForm.lastName  = "aitechtonic";
            } );
</script>

</body>
</html>

This example binds the two input fields in the form to the $scope.myForm.firstName and $scope.myForm.lastName properties. The two properties both have a value set in the controller function. These values will be displayed in the input fields when the page is first rendered. When the user types in something in the text fields it will get copied into the these properties too.

The example also contains two interpolation directives ({{}}). These two directives will insert the value of the myForm.firstName and myForm.lastName below the form fields. When you enter something in the text boxes it will be copied into the myForm.firstName and myForm.lastName properties. From there it will be inserted into the HTML by the two interpolation directives. This data binding happens while the user enters data in the form fields, so the interpolation directives will update the values while typing (this looks cool, but I cannot remember the last time I actually needed this in a web app form).

❰ Previous Next ❱