javascript 如何检查表单字段是否在 Angular 中被触摸和为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30140379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:47:03  来源:igfitidea点击:

How to check if form field is touched and empty in Angular

javascriptangularjs

提问by Pekka

I want to warn the user if the form field is touched and left empty. I can check if the empty field is touched with $pristine. But if I preload form data from $scope, $pristinedoesn't work. Also, I don't want to use requiredparameter, I only want to inject warning-style with ng-class.

如果表单字段被触摸并留空,我想警告用户。我可以检查空字段是否与$pristine. 但是,如果我从 预加载表单数据$scope$pristine则不起作用。另外,我不想使用required参数,我只想用ng-class.

<div ng-class="{'has-warning': !form.name.$pristine}">
  <input type="text" name="name" ng-model="people.name">
</div>

回答by Rob J

There are several state properties set on the ngModel described here. You may want to consider using form.name.$dirty or form.name.$touched instead.

此处描述的 ngModel 上设置了多个状态属性。您可能需要考虑使用 form.name.$dirty 或 form.name.$touched 代替。

edit

编辑

Try using:

尝试使用:

ng-class="{'has-warning': form.name.$touched && people.name.length === 0}"

回答by rhel.user

I would suggest to use :

我建议使用:

form.name.$touched && form.name.$invalid

it should work

它应该工作

回答by Tyler O

You can try using ngFocus:

您可以尝试使用 ngFocus:

Specify custom behavior on focus event.

指定焦点事件的自定义行为。

https://docs.angularjs.org/api/ng/directive/ngFocus

https://docs.angularjs.org/api/ng/directive/ngFocus

<div ng-class="{'has-warning': !form.name.isValid}">
  <input type="text" name="name" ng-model="people.name" ng-focus="form.name.isValid = people.name ? true : false">
</div>