AngularJS - 原始/肮脏和触摸/未触摸之间的区别

时间:2014-07-29 21:14:47

标签: angularjs

AngularJS Developer Guide - Forms告诉我有很多关于表单和字段的样式和指令。对于每一个,CSS类:

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

pristine/dirtytouched/untouched之间的区别是什么?

5 个答案:

答案 0 :(得分:187)

AngularJS Developer Guide - CSS classes used by AngularJS

  
      
  • @property {boolean} $ untouched如果控件尚未失去焦点,则为真。
  •   
  • @property {boolean} $ touch如果控件失去焦点,则为真。
  •   
  • @property {boolean} $ pristine如果用户尚未与控件进行交互,则为True。
  •   
  • @property {boolean} $ dirty如果用户已经与控件进行了交互,则为真。
  •   

答案 1 :(得分:81)

$pristine / $dirty告诉您用户是否实际更改任何内容,而$touched / $untouched告诉您用户是否仅< em>去过/访问过。

这对验证非常有用。 $dirty的原因总是避免在用户实际访问某个控件之前显示验证响应。但是,通过仅使用$dirty属性,用户将无法获得验证反馈,除非他们实际更改了值。因此,如果用户没有更改/与值互动,$invalid字段仍然不会向用户显示提示。如果用户完全忽略了必填字段,那么一切都很好。

使用Angular 1.3和ng-touched,您可以在用户模糊时立即在控件上设置特定样式,无论他们是否实际编辑了该值。

这是一个显示行为差异的CodePen

答案 2 :(得分:2)

在专业版Angular-6 book中的详细信息如下:

  • 有效:如果元素的内容有效,则此属性返回 true ,否则返回false。
  • 无效:如果元素的内容无效,则此属性返回 true ,否则返回false。

  • 原始:如果元素的内容未更改,则此属性返回 true

  • :如果元素的内容已更改,此属性将返回 true
  • 未修改:如果用户尚未访问元素,则此属性返回 true
  • 感动:如果用户访问过元素,则此属性返回 true

答案 3 :(得分:2)

这是一个迟到的答案,但希望这可能会有所帮助。

场景一: 您是第一次访问该站点并且没有接触任何字段。表单状态为

ng-untouched 和 ng-pristine

场景 2: 您当前正在表单的特定字段中输入值。那么状态是

ng-untouched 和 ng-dirty

场景 3: 您已完成在字段中输入值并移至下一个字段

ng-touched and ng-dirty

场景 4: 假设一个表单有一个电话号码字段。您输入了号码,但实际上输入了 9 位数字,但电话号码需要 10 位数字。然后状态为 ng-无效

简而言之:

ng-untouched:当表单域还没有被访问过时

ng-touched:当表单域被访问时AND该域失去焦点

ng-pristine:表单字段值不改变

ng-dirty:更改表单字段值

ng-valid : 当表单域的所有验证都成功时

ng-invalid:当表单域的所有验证都不成功时

答案 4 :(得分:0)

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

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.
相关问题