javascript ng-touched 不工作 - AngularJS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28694175/
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 09:23:07  来源:igfitidea点击:

ng-touched not working - AngularJS

javascriptangularjs

提问by Fahad Khan

Form fields not being added ng-touchedclass, instead remains ng-pristine

表单字段没有被添加ng-touched类,而是保留ng-pristine

This is my form:

这是我的表格:

<form novalidate class="css-form">

            <div class="form-group clearfix">
                <label class="col-xs-12 col-sm-6 col-md-4">State Code</label>
                <div class="col-xs-12 col-sm-6 col-md-8">
                    <input type="text" class="form-control" ng-maxlength="2" ng-model="ObjectNew.stateCode" required>
                </div>
            </div>
            <div class="clearfix"></div>

            <div class="form-group clearfix">
                <label class="col-xs-12 col-sm-6 col-md-4">Zip</label>
                <div class="col-xs-12 col-sm-6 col-md-8">
                    <input type="text" class="form-control" ng-model="ObjectNew.zip" required>
                </div>
            </div>
            <div class="clearfix"></div>

        </form>

When I see in inspect element, it does show only ng-pristineclass on each field, even if i went through both fields and leaves null. It shows ng-invalidtoo, which is fine.

当我在检查元素中看到时,它确实只ng-pristine在每个字段上显示类,即使我浏览了两个字段并留下空值。它也显示ng-invalid,这很好。

Have to add the styles actually:

实际上必须添加样式:

.css-form input.ng-invalid.ng-touched {
    background-color: #FA787E !important;
    }

  .css-form input.ng-valid.ng-touched {
    background-color: #78FA89 !important;
  }

回答by kamituel

The term pristineand touchedare not similar. An input will remain pristineas long as it has not been modified. It is untouched, as long as it didn't loose focus - Angular doc statesthat ng-touchedis applied when "the control has been blurred".

术语pristinetouched不相似。pristine只要输入未被修改,它就会一直存在。它untouched,只要它没有松动的焦点-角DOC状态ng-touched当“控制一直是模糊的”应用。

So it is possible for an input to be pristine and touched - just click it, and then click somewhere else without typing anything in.

因此,输入可能是原始的和触摸的 - 只需单击它,然后单击其他位置而不输入任何内容。

It is also possible for it to be dirty and untouched - click it, type in some text, but do notclick anywhere else.

也有可能它很脏而且没有被触及 - 单击它,输入一些文本,但不要单击其他任何地方。

To see that, and see working ng-touchedin action, refer to this jsFiddle.

要查看并查看实际工作ng-touched,请参阅此jsFiddle

To make sure it works, use Angular 1.3 as pointed out by @dfsq. Also, use angular-touchwhich matches your Angular version. The JSFiddle above works correctly.

为了确保它有效,请使用@dfsq 指出的 Angular 1.3。另外,使用angular-touch与您的 Angular 版本匹配的版本。上面的 JSFiddle 工作正常。