Chapter 5
Creating Advance Form
AngularJS 与传统表单比较
- 传统的表单输入元素的值会在表单提交时送往服务器;
- AngularJS为模型和视图解耦,让输入指令关心如何显示输入值,AngularJS根据输入值的变化更新模型。
ngModel directive
- ngModel 指令实现了数据的双向绑定。
input directive
- Adding the
required
validation
<input class="span6" type="text" name="firstName" ng-model="user.firstName" required>
- 基于文本的输入可以设置如下属性:
ng-minlength
,ng-maxlength
,ng-pattern
- checkbox inputs
<input type="checkbox" ng-model="user.admin"><span class="help-inline">Admin</span>
- radio inputs
<label><input type="radio" ng-model="user.sex" value="male"/>Male</label>
- select inputs
<label>Select a user value with email for label</label>
<select ng-model="chosenUser" ng-options="user.email for user in users"></select>
Selected User: {{ chosenUser }}
- select and the empty options
<label>Select a letter (custom empty option)</label>
<select ng-model="letter" ng-options="letter for letter in letters">
<option value=""> -- </option>
</select>
- hidden the empty options
<label>Select a letter (custom empty option)</label>
<select ng-model="letter" ng-options="letter for letter in letters">
<option style="display:none" value=""></option>
</select>
Validating AngularJS forms
- Directives:
ng-disabled
按钮无效;novalidate
关闭浏览器验证
Nesting forms in other forms:
- Directive:
ng-form
- 将子表单放到`script`块中;
- 直接使用;
- Directive:
controller
$scope.getCssClasses = function(ngModelContoller) {
return {
error: ngModelContoller.$invalid && ngModelContoller.$dirty,
success: ngModelContoller.$valid && ngModelContoller.$dirty
};
};
- Repeating subforms
<div class="input-append" ng-repeat="website in user.websites">
<input type="url" ng-model="website.url"/><button class="btn" ng-click="remove($index)">X</button>
</div>
- Validating repeated inputs
Form submission
- 直接向服务器提交表单,如果表单包含了
active
属性,表单会向active
所定义的URL进行正常提交;
<form method="get" action="http://www.google.com/search">
<input name="q"> Press enter in the input to submit
</form>
ngSubmit
,在表单中应用;ngClick
, 在button
和input[type="submit"]
;Reseting the User Info Form