gpt4 book ai didi

javascript - 如何在 AngularJS 的表单验证中隐藏/显示帮助消息?

转载 作者:行者123 更新时间:2023-11-30 16:20:17 25 4
gpt4 key购买 nike

我已将 ngMessages 包含到我的 AngularJS 应用程序中以进行一些表单验证。它非常有用,但是我遇到了一些我无法真正理解的东西。

假设我的表单中有这段代码,名为:testForm

<input type="text" name="test1" class="form-control" ng-model="test1" required>

<span class="help-block" ng-hide="testForm.test1.$error">Please enter the a test name</span>

<div ng-messages="testForm.test1.$error" ng-if="testForm.test1.$dirty">
<div class="text-danger" ng-message="required">This field is required</div>
</div>

我想在此文本框中出现错误时隐藏帮助消息,除非用户尚未开始键入任何内容(在 $dirty 上)。

这怎么可能?使用上面的代码,我的 testForm.test1.$error 总是给我 true 值,即使它是空的,因此总是隐藏它。

我在这里错过了什么?

编辑:

我正在澄清更多我想要实现的目标:

  • 键入时,帮助消息应该可见,错误消息应该隐藏
  • 当出现错误时,隐藏帮助信息,显示错误信息
  • 当什么都没有被触摸时,帮助信息应该是可见的,错误信息应该是隐藏的

最佳答案

您是否尝试过 ng-hide="testForm.test1.$error && testForm.test1.$dirty"?这样,当输入字段干净(不脏)时,消息始终显示。


编辑:据我所知,当输入字段具有焦点时,您希望消息可见。

在你的 Controller 中,将 hasFocus 初始化为 false:

$scope.hasFocus = false;

在您的 HTML 文件中:

<input type="text" name="test1" class="form-control" ng-model="test1" 
ng-focus="hasFocus=true" ng-blur="hasFocus=false" required>

<span class="help-block" ng-hide="!hasFocus && testForm.test1.$error && testForm.test1.$dirty">Please enter the a test name</span>

<div ng-messages="testForm.test1.$error" ng-if="testForm.test1.$dirty">
<div class="text-danger" ng-message="required">This field is required</div>
</div>

如果适合您,您可以按如下方式替换 ng-hide。当 test1 不为空和有错误时,它会隐藏消息。

ng-hide="!hasFocus && testForm.test1.$error && test1"

关于javascript - 如何在 AngularJS 的表单验证中隐藏/显示帮助消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34845564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com