Angularjs中input的指令和屬性

2021-09-06 14:58:02 字數 3464 閱讀 9389

建議新增 novalidate屬性(可無值)到form標籤上,這樣可以保證在表單不合法的情況下阻止瀏覽器繼續提交資料。

可以給表單元素 input 新增 required 屬性(可無值),讓該表單成為必填項,如:

<

form

action

=""name

="formname"

novalidate ng-controller

="test"

>

<

input

type

="text"

name

="name"

ng-model

="use.name"

required

>

form

>

angularjs中表單最常用的就是用 ng-model 屬性進行雙向繫結了。用 ng-model 繫結資料後,可以時時的和資料進行互動。

使用 ng-model 屬性進行繫結的表單,會自動的新增一些 class 樣式,如:

非必填表單

初始化時會新增 .ng-pristine 和 .ng-valid 兩個class樣式。當表單為非空時 class 樣式會變成 .ng-valid 和 .ng-dirty 。其中將 .ng-pristine 變成了 .ng-dirty 。

必填表單

初始化時會新增 .ng-pristine 、.ng-invalid 和 .ng-invalid-required 三個class樣式。當表單為非空時 class 樣式會變成 .ng-dirty 、.ng-valid 和 .ng-valid-required 。

以上 class 樣式還只是針對預設的input(即type=text的input),像那些特殊意義的 input ,如:type=email、type=number等。其 class 樣式的種類會更多。

angular input最小長度

<

input

type

="text"

ng-minlength

="5"

/>

angular input最大長度

<

input

type

="text"

ng-maxlength

="5"

/>

angular表單匹配正規表示式

<

input

type

="text"

ng-pattern

="/a-za-z"

/>

angularjs通過dom元素上設定乙個表單,從而使我們可以很容易的獲取到當前 $scope 物件的屬性。

判斷表單未修改

<

form

action

=""name

="formname"

novalidate ng-controller

="test"

>

<

input

type

="text"

name

="name"

ng-model

="use.name"

required

>

<

input

type

="button"

value

="檢視"

ng-click

="fn(formname.name.$pristine);"

>

form

>

<

script

>

function

test($scope)

}script

>

執行以上**,formname.name.$pristine 會返回乙個布林值。

因為 formname 是當前域(test)中 $scope 物件的屬性,所以我們也可以用如下方法來獲取 $pristine 值,以檢視值是否有改變。如:

<

form

action

=""name

="formname"

novalidate ng-controller

="test"

>

<

input

type

="text"

name

="name"

ng-model

="use.name"

required

>

<

input

type

="button"

value

="檢視"

ng-click

="fn();"

>

form

>

<

script

>

function

test($scope)

}script

>

如下一些屬性與 $pristine 屬性類似,如 $dirty、$valid等。

判斷表單修改過 $dirty 屬性。

判斷表單合法 $valid 屬性。

判斷表單非法 $invalid 屬性。

判斷表單錯誤 $error 屬性。如果某個驗證失敗,則這個屬性返回true,相反如果這個屬性為false,則代表驗證通過。

$error 屬性是乙個非常有用的屬性,如:

<

form

action

=""name

="testemail"

novalidate ng-controller

="testemail"

>

<

input

type

="email"

name

="email"

ng-model

="us.email"

required

>

<

input

type

="button"

value

="列印"

ng-click

="printemail()"

>

form

>

<

script

>

function

testemail($scope)

}script

>

如果 $error 是獲取 type=email 的屬性,則會返回這樣乙個物件:object ,其中返回的物件包含乙個 required 和 email 屬性。如果是獲取 type=number 的屬性則物件包含的屬性則是 required 和 number 。

Angularjs中input的指令和屬性

建議新增 novalidate屬性 可無值 到form標籤上,這樣可以保證在表單不合法的情況下阻止瀏覽器繼續提交資料。可以給表單元素 input 新增 required 屬性 可無值 讓該表單成為必填項,如 form action name formname novalidate ng contro...

AngularJS中ng class使用方法

有三種方法 1 通過 scope繫結 不推薦 2 通過物件陣列繫結 3 通過key value鍵值對繫結 實現方法 function ctrl scope 2 通過物件陣列繫結 function ctrl scope 當isselected為true時,增加selected樣式 當isselecte...

angularJs中的ng repeat的使用

最近專案中要求做乙個下拉的城市選擇的功能,由於專案使用了angularjs框架,所以自然而然的想到 ng repeat 指令,免去了自己寫迴圈的煩惱。所以總結一下 ng repeat 的使用方法 如下 ng repeat directive 城市選擇 請選擇城市 這應該是最簡單的ng repeat的...