AngularJS - difference between pristine/dirty and touched/untouched

后端 未结 4 832
生来不讨喜
生来不讨喜 2020-11-30 17:32

AngularJS Developer Guide - Forms tell there are many styles and directives regarding forms and fields. For each one, a CSS class:

ng-valid
ng-invalid
ng-pri         


        
4条回答
  •  情歌与酒
    2020-11-30 17:56

    $pristine/$dirty tells you whether the user actually changed anything, while $touched/$untouched tells you whether the user has merely been there/visited.

    This is really useful for validation. The reason for $dirty was always to avoid showing validation responses until the user has actually visited a certain control. But, by using only the $dirty property, the user wouldn't get validation feedback unless they actually altered the value. So, an $invalid field still wouldn't show the user a prompt if the user didn't change/interact with the value. If the user entirely ignored a required field, everything looked OK.

    With Angular 1.3 and ng-touched, you can now set a particular style on a control as soon as the user has blurred, regardless of whether they actually edited the value or not.

    Here's a CodePen that shows the difference in behavior.

提交回复
热议问题