Form 表单中有很多元素,最普遍的Input,CheckBox,Radio,Select等等。Angular的Form有什么特殊之处呢?
Input的属性有:
name 名字
type 类型(HTML5里有的类型: number,url,email)
ng-model 绑定的数据
required/ng-required 是否必填
ng-minlength 最小长度
ng-maxlength 最大长度
ng-pattern 匹配模式
ng-change 值变化时的回调
例子(输入长度5-15的起始为abc的内容):
1
|
<input
type=
"text" name=
"a" required ng-model=
"a" required ng-minlength=5 ng-maxlength=15 ng-pattern=
"/abc/"/>
|
Checkbox
Checkbox只有两种值,选中和不选中。
使用方法:
1
2
3
4
5
6
7
|
<input
type=
"checkbox" name=
"checkbox" ng-model=
"checkbox_value" ng-true-value=
"AA" ng-false-value=
"BB"/>
<span>{{ checkbox_value }}</span>
$scope.checkbox_value =
'AA';
|
Radio
与checkbox的区别,一个radio只有一个值
1
2
3
|
<input
type=
"radio" name=
"radio_test" ng-model=
"radio_test" value=
"AA"/>AA
<input
type=
"radio" name=
"radio_test" ng-model=
"radio_test" value=
"BB"/>BB<br>
radio选中的值为:<span>{{ radio_test }}</span>
|
Textarea
与Input类似,但是可以拉伸
Select
使用ng-options遍历数组
x for x in 数组名(普通数组)
1
2
3
4
5
|
<div ng-init=
"o=[0,1,2,3]; a=o[1];">
<select ng-model=
"select_test" ng-options=
"x for x in o" ng-change=
"show()">
<option value=
"">可以加这个空值</option>
</select>select选中的值为: {{ select_test }}
</div>
|
x.name for x in 数组名(对象数组,有key,value)
1
2
3
4
|
<div ng-init=
"o2=[{name: 'AA'}, {name: 'BB'}]; a=o2[1];">
<select ng-model=
"select_test2" ng-options=
"x.name for x in o2">
</select>select选中的值为: {{ select_test2 }}
</div>
|
x.v as x.name for x in 数组名(选择框显示的是name的值,但选中的value值是v的值)
1
2
3
4
|
<div ng-init=
"o3=[{name: 'AA', v: '00'}, {name: 'BB', v: '11'}]; a=o3[1].v;">
<select ng-model=
"select_test3" ng-options=
"x.v as x.name for x in o3">
</select>select选中的值为: {{ select_test3 }}
</div>
|
x.name group by x.g for x in 数组名(根据g的值来分组)
1
2
3
4
|
<div ng-init=
"o4=[{name: 'AA', g: '00'},{name: 'BB', g: '11'},{name: 'CC', g: '00'}]; select_test4=o4[1];">
<select ng-model=
"select_test4" ng-options=
"x.name group by x.g for x in o4">
</select>select选中的值为: name值是{{ select_test4.name }};value是{{ select_test4.g }}
</div>
|
x.v as x.name group by x.g for x in 数组名(分组了还分别指定显示与值的,根据g分组,v的值是value值,name值是显示的内容)
1
2
3
4
|
<div ng-init=
"o5=[{name: 'AA', g: '00', v: '='}, {name: 'BB', g: '11', v: '+'},{name: 'CC', g: '00', v: '!'}]; select_test5=o5[1].v;">
<select ng-model=
"select_test5" ng-options=
"x.v as x.name group by x.g for x in o5">
</select>select选中的值为: {{ select_test5 }}
</div>
|
v.v as v.name group by v.g for (k, v) in 对象名(o6是一个对象,对象中有两个(key:value)对,可以取对象的值来遍历)
1
2
3
4
5
6
7
8
9
|
<div ng-init=
"o6={a: {name: 'AA', v: '00', g: '=='},b: {name: 'BB', v: '11', g: '=='}}; select_test6=o6.a.v;">
参数是对象<br>
显示对象的值里的v的值<br>
<select ng-model=
"select_test6" ng-options=
"v.v as v.name group by v.g for (k, v) in o6">
</select>select选中的值为: {{ select_test6 }}、
显示对象的名字<br>
<select ng-model=
"select_test7" ng-options=
"k for (k, v) in o6">
</select>select选中的值为: {{ select_test7 }}
</div>
|
Github参考代码
转自我的Github博客