Angular Form With Examples

Today we will look into Angular Form elements. We are all familiar with HTML forms and its usage. Therefore, I’m not going to discuss about the input controls in detail. In this post, we are going to discuss about forms in the AngularJS context.

A form is a collection of input controls like input, select, textarea. These input controls are ways for a user to enter data and a form is used for grouping related controls together.

Angular Form

We have already seen some of the AngularJS features for binding data of HTML form input fields to the model object. These features make the developer’s task easier when working with forms.

We use ng-model directive to bind an input field to a model property.

Angular form text fields

You are very much familiar with binding input text field to the model property and the value can be displayed using an expression within a pair of curly braces like {{form.name }}

This binding is bi-directional; meaning any change in the model is reflected in the view and vice versa.

Angular Form Check boxes

The model property will be set to true if the check box is checked otherwise false. You can use the ng-true-value and ng-false-value directives if you want to use other values instead of true and false. We can use this in the following way:

In this example, the model property will be set to “yes” if it is checked otherwise it will be set to “no”.

Angular Form Binding Radio buttons

We use ng-model directive to bind the selected radio button value to the model property.

The form.gender will be set to male if we checked the radio button value equals male otherwise female.

Angular Form Example

The following example demonstrates a simple form using angular features.

  1. Define a FormController in the formApp.
  2. We use two objects to handle the forms, master and employee and initially master object is set to empty.
  3. Two methods save and reset is used in this example.
  4. angular.copy is a function in the ng module used to create a deep copy of source, which should be an object or an array.
  5. We bind the input value to the employee object and it is copied to the master object when we click on the save button.
  6. The reset function will reset the fields with the values we entered before clicking the save button.

app.js

The following HTML contains the form controls we used in our example and you can see how the binding takes place using the angular features.

index.html

The following code uses angularJS Filter feature to display the objects in JSON format.

You will see the following output on your browser.

That’s all for angular form, we will see the angularJS form validation in the next tutorial.

By admin

Leave a Reply

%d bloggers like this: