What’s a form? Well, it’s just a container that groups several related input controls together. A control is an HTML element (such as
textarea) that lets users enter data. You already know angularjs provides us with the very useful
ng-model directive that keeps the input control value and
scope model in sync. So, to begin with, let’s see how you can use
ng-model with different input controls.
Please note that in the following examples, the
<form> element isn’t doing anything extra. All the data bindings will still work without
<form>. Later on, we will see how the
<form> element is useful.
text area controls
As you’ve already seen, to tie the input control value to a
scope model, you need to attach the
ng-model directive to it:
<form name="myform"> <input type="text" name="firstname" ng-model="user.firstname" /> </form>
By doing this you bind the
input field’s value to the
textarea can also be bound to a
scope model in exactly the same way:
<form name="myform"> <textarea name="bio" ng-model="user.bio"></textarea> </form>
Now, let’s see some more controls we haven’t used so far.
To bind the selected option of a
<select> element to the
scope model you need to use the
ng-model directive as follows.
<form name="myform"> <select name="country" ng-model="user.country"> <option value="US">United States</option> <option value="GB">United Kingdom</option> <option value="AU">Australia</option> </select> </form>
In this case whatever value you select is passed to the
$scope.user.country model. There is nothing extra you need to do. angularjs automatically detects the currently selected option and sets it to the
Handling Empty Options
One of the common problems encountered while dealing with
<select> is that, initially, angularjs automatically inserts an empty
<option> to the
<select>. This is because, to begin with,
$scope.user.country doesn’t match any option values. So, in the above example, you’ll see an empty option in addition to the three country options. To ensure this doesn’t happen you can insert something like this to the
<select name="country" ng-model="user.country"> <option value="">Please select an option</option> <option value="US">United States</option> <option value="GB">United Kingdom</option> <option value="AU">Australia</option> </select>
If you do this, the first option in the select drop down will be
Please select an option rather than an empty value.