1. 程式人生 > >angular 表單元素,例如checkbox,radio,select等用法

angular 表單元素,例如checkbox,radio,select等用法

Form 表單中有很多元素,最普遍的Input,CheckBox,Radio,Select等等。Angular的Form有什麼特殊之處呢?

Input

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只有兩種值,選中和不選中。

使用方法:

1234567 # HTML5: <input type="checkbox" name="checkbox" ng-model="checkbox_value" ng-true-value="AA" ng-false-value="BB"/> <span>{{ checkbox_value }}</span># JS:
$scope.checkbox_value = 'AA'; #controller中的初始化值會關係到控制元件狀態(雙向繫結)

Radio

與checkbox的區別,一個radio只有一個值

123 <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 陣列名(普通陣列)

12345 <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)

1234 <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的值)

1234 <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的值來分組)

1234 <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值是顯示的內容)

1234 <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)對,可以取物件的值來遍歷)

123456789 <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參考程式碼