Angular,如何有条件地设置必填字段的样式? [英] Angular, how to conditionally style a required field?

查看:83
本文介绍了Angular,如何有条件地设置必填字段的样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在按下提交按钮之前,我不希望显示对表单的验证.按下按钮后,应提交表单(如果有效),否则应提交无效字段,并以红色突出显示.

I do not want to display validation of my form until the submit button is pressed. When the button is pressed the form should be submitted if valid, and if not submitted invalid fields should become highlighted in red.

出于遗留原因,我正在导入一个css文件,该文件定义了带有红色背景的 input:invalid ,因此任何标记为 required 的输入字段都将始终显示为红色.

For legacy reasons, I am importing a css file which defines input:invalid with a red background, as a result any input field marked as required will always display as red.

我试图通过有条件地设置 ng-required 来使此工作变得更简单.这多少有些用,除了第一次单击提交按钮时,$ valid表单的评估结果为 true .

I attempt to make this work in the below fiddle by conditionally setting ng-required. Which somewhat works, with the exception that the first time the submit button is clicked the form $valid evaluates to true.

如何有条件地设置 ng-required ,以便仅在单击提交按钮后才设置字段的样式,并且 $ valid 格式始终根据以下内容正确求值:字段为空/非空?

How can I conditionally set ng-required such that my field is only styled after the submit button has been clicked, and the form $valid consistently evaluates correctly based on the field being empty/non-empty?

https://jsfiddle.net/dk89dhp2/19/

推荐答案

您有两个问题.第一个就是错字.

You have two issues. The first is simply a typo.

此:

ng-required="myForm.showErrors"

应为:

ng-required="showErrors"

以匹配模型中的内容.

修复此问题后,您会注意到它几乎可以正常工作,除了对话框指出该表单在不应该使用时是有效的.为了使摘要循环有运行的机会,您可以将需要执行的所有操作包装在 $ timeout 中.(也可以使用设置 showErrors 的值的代理函数,然后从 $ timeout 调用提交函数)

Once you fix this, you will notice it almost works except the dialog says the form is valid when it should not. To give the digest cycle a chance to run, you can wrap whatever you need to do in a $timeout. (Could also use a proxy function that sets the value of showErrors then calls the submit function from a $timeout)

$scope.myForm.submit = function() {
  $scope.showErrors = true;
  $timeout(function() {
    alert("form validity is: " + $scope.myFormNg.$valid);
  });
};

更新了jsfiddle

这篇关于Angular,如何有条件地设置必填字段的样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆