Advanced Editing with Forms
In our previous example we made a very simple form. What if we wish to make something more complex? Here we would like the user to store an ingredient list for single serving, and then let the form compute ingredient amount needed for n-servings.
<html>
<head>
<script type="text/javascript"
src="http://angular.getangular.com/angular-1.0a.js#database=docsdb"></script>
</head>
<body>
<div ng-entity="recipe=Recipe"></div>
Name: <input name="recipe.name"><br>
Category: <select name="recipe.category">
<option value="main">Main Dish</option>
<option value="appetizer">Appetizer</option>
<option value="desert">Desert</option>
<option value="salad">Salad</option>
</select><br>
You will need {{recipe.ingredients.length}} ingredients when making {{recipe.name}}.
<table>
<tr>
<th> </th>
<th>Ingredient</th>
<th>Qty</th>
<th>Units</th>
<th>Need</th>
</tr>
<tr ng-repeat="ingredient in recipe.ingredients">
<td>[<a href="#" ng-action="recipe.ingredients.$remove(ingredient)">X</a>]</td>
<td><input name="ingredient.name" ng-require></td>
<td><input name="ingredient.qty" ng-require ng-validate="number" size="4"></td>
<td>
<select name="ingredient.unit">
<option value="cup">Cups</option>
<option value="tblspn">Table Spoons</option>
<option value="tspn">Tea Spoons</option>
</select>
</td>
<td>{{ingredient.qty * servings|number}}</td>
</tr>
<tr>
<td> </td>
<td>[<a href="" ng-action="recipe.ingredients.$add()">Add another ingredient</a>]</td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
Display for <input name="servings" ng-require ng-validate="number" size="3" value="1"> servings.<br>
Instructions: <br>
<textarea name="recipe.instructions" cols="50" rows="5"></textarea> <br>
<input type="submit" value="Save">
<hr>
Debug Information:
<pre>servings = {{servings}}</pre>
<pre>recipe = {{recipe}}</pre>
</body>
</html>
Repeater
A single recipe has one or more ingredients. Since the count is different for each recipe, we need a way to let the user control the structure of both the template as well as the document. The ng-repeat allows you to replicate a portion of the document any number of times. Notice that when ng-repeat binds to the document it automatically creates an Array in that location. To add a new row we use recipe.ingredients.$add(); to remove a row we use recipe.ingredients.$remove(ingredient). These actions are triggered by clicking on the link having attribute ng-action.
Scope
When ng-repeat unrolls it assigns each ingredient to a local scope variable ingredient. The ingredient variable only has value within the ng-repeat scope.
Also notice, that we have created a servings variable, which is not part of a document. This means that its value will not be persisted when you save the document or reopen it.