javascript Angularjs - 当字段无效时突出显示字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19462214/
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
Angularjs - highlight field when field not valid
提问by user686483
I'm new to Angular and would like to know how I can highlight form fields when the validation fails.
我是 Angular 的新手,想知道如何在验证失败时突出显示表单字段。
I have created a fiddleto illustrate what I'm after.
我创建了一个小提琴来说明我所追求的。
Any help is appreciated.
任何帮助表示赞赏。
<p>
<label for="name">User:</label>
<input type="text" name="name" ng-model="name"
required ng-minlength="5" ng-maxlength="32">
<span ng-show="register.name.$error.required" class="err">
Required</span>
<span ng-show="register.name.$error.minlength" class="err">
Minimum 5 characters</span>
<span ng-show="register.name.$error.maxlength" class="err">
Maximum 32 characters</span>
</p>
回答by Khanh TO
In your case, you could try ng-class:
在你的情况下,你可以尝试 ng-class:
<input type="text" ng-class="{highlight:register.name.$error.required || register.name.$error.minlength || register.name.$error.maxlength}" name="name" ng-model="name"
required ng-minlength="5" ng-maxlength="32">
Another solution is to style on these classes:
另一个解决方案是在这些类上设置样式:
ng-valid
ng-invalid
ng-pristine
ng-dirty
Angular automatically toggles these classes based on current validation status. Below is the demo to hightlight invalid inputs:
Angular 会根据当前的验证状态自动切换这些类。以下是突出显示无效输入的演示:
input.ng-invalid {
background:#F84072;
border: 2px red solid;
}