AngularJS form 指令

定义和用法

AngularJS 修改 <form> 元素的默认行为。

AngularJS 应用程序内的表单被赋予了某些属性。这些属性描述了表单的当前状态。

表单有以下状态:

  • $pristine 尚未修改任何字段
  • $dirty One or more fields have been modified
  • $invalid Form content is invalid
  • $valid Form content is valid
  • $subscribed 表单已提交

每个状态的值代表一个布尔值,为 truefalse

如果未指定 action 属性,AngularJS 中的表单会阻止默认操作,即向服务器提交表单。

实例

例子 1

只要所需的输入字段为空,此表单的“有效状态”就不会被视为 "true":

<form name="myForm">
<input name="myInput" ng-model="myInput" required>
</form>
<p>表单的有效状态是:</p>
<h1>{{myForm.$valid}}</h1>

Try it yourself

例子 2

将样式应用于未修改的(原始)表单和修改后的表单:

<style>
form.ng-pristine {
    background-color: lightblue;
}
form.ng-dirty {
    background-color: pink;
}
</style>

Try it yourself

Syntax

<form name="formname</form>

By using name The value of the attribute to refer to the form.

CSS Classes

Forms within AngularJS applications are assigned certain classes. These classes can be used to set form styles based on their state.

The following classes have been added:

  • ng-pristine No fields have been modified
  • ng-dirty One or more fields have been modified
  • ng-valid Form content is valid
  • ng-invalid Form content is invalid
  • ng-valid-key Verify each key every time. For example:ng-valid-requiredIt is very useful when there are more than one item to be verified.
  • ng-invalid-key For example:ng-invalid-required

If the value represented by the class is falseIf these classes are deleted.