AngularJS -原始/脏和接触/未接触之间的差异

l7mqbcuq  于 2022-10-31  发布在  Angular
关注(0)|答案(5)|浏览(138)

AngularJS Developer Guide - Forms列出了许多关于表单和字段的样式和指令。对于每一个样式和指令,都有一个CSS类:

ng-valid
ng-invalid
ng-pristine
ng-dirty
ng-touched
ng-untouched

pristine/dirtytouched/untouched之间有什么区别?

0lvr5msh

0lvr5msh1#

AngularJS Developer Guide - CSS classes used by AngularJS

  • @property {boolean} $untacted如果控件尚未失去焦点,则为True。
  • @property {boolean} $touched如果控件失去焦点,则返回True。
  • @property {boolean} $pristine如果用户尚未与控件交互,则为True。
  • @property {boolean} $dirty如果用户已经与控件交互,则为True。
anauzrmj

anauzrmj2#

$pristine/$dirty告诉您用户是否实际 * 更改了 * 任何内容,而$touched/$untouched告诉您用户是否只是 * 去过/访问过 *。
这对于验证非常有用。使用$dirty的原因是,在用户实际访问某个控件之前,总是避免显示验证响应。但是,如果只使用$dirty属性,用户将不会得到验证反馈,除非他们实际更改了该值。因此,$invalid字段在用户不修改或不与该值交互的情况下仍然不会向用户显示提示。
使用Angular 1.3和ng-touched,现在只要用户访问并模糊了控件,就可以在控件上设置特定的样式,而不管他们是否实际编辑了该值。
这里有一个CodePen,它显示了行为上的差异。

brvekthn

brvekthn3#

在Pro Angular-6 book中的详细说明如下;

valid:如果元素的内容有效,则此属性返回true*,否则返回false。**
无效:如果元素的内容无效,则此属性返回true*,否则返回false。**
质朴:如果元素的内容尚未更改,则此属性返回true*
dirty:如果元素的内容已更改,则此属性返回true
敬谢不敏:如果用户尚未访问该元素,则此属性返回true
*
感动:如果用户已访问该元素,则此属性返回true*。**

kb5ga3dv

kb5ga3dv4#

这是一个迟来的答案,但希望这可能会有所帮助。
场景1:您第一次访问站点,没有触摸任何字段,表单状态为

ng-未触及和ng-原始

案例2:您目前正在表单的特定字段中输入值。然后状态为

ng-未接触和ng-脏

场景3:在字段中输入完值后,移到下一个字段

NG-接触和NG-脏

案例4:假设表单有一个电话号码字段。您输入了号码,但实际上输入了9位数字,而电话号码需要10位数字。则状态为ng-invalid
简而言之:

ng-intacted:当表单域尚未被访问时
感动:当访问表单域时并且该域已失去焦点
ng-原始:表单域值未更改
ng-dirty:表单域值已更改
ng-有效:当表单字段的所有验证都成功时
ng-无效:当表单域的任何验证不成功时

7cwmlq89

7cwmlq895#

值得一提的是the validation properties are different for forms and form elements(注意,touched和untouched仅适用于字段):

Input fields have the following states:

$untouched The field has not been touched yet
$touched The field has been touched
$pristine The field has not been modified yet
$dirty The field has been modified
$invalid The field content is not valid
$valid The field content is valid

They are all properties of the input field, and are either true or false.

Forms have the following states:

$pristine No fields have been modified yet
$dirty One or more have been modified
$invalid The form content is not valid
$valid The form content is valid
$submitted The form is submitted

They are all properties of the form, and are either true or false.

相关问题