gpt4 book ai didi

angularjs - Angular - ng-messages 中的多个字段

转载 作者:行者123 更新时间:2023-12-01 12:29:01 24 4
gpt4 key购买 nike

我正在使用 ng-messages 并想知道是否可以在一个代码块中检查多个字段而不必重复:

所以我有:(注意 checkCustom 是我写的自定义指令)

<div ng-messages="registrationForm.field1.$error" ng-if="registrationFormValid">
<span ng-message="required">please enter field 1</span>
<span ng-message="checkCustom">please check custom value</span>
</div>

<div ng-messages="registrationForm.field2.$error" ng-if="registrationFormValid">
<span ng-message="required">please enter field 1</span>
<span ng-message="checkCustom">please check custom value</span>
</div>

不过我更喜欢这样的东西:

<div ng-messages="registrationForm.field1.$error || registrationForm.field2.$error" ng-if="registrationFormValid">
<span ng-message="required">please enter field 1</span>
<span ng-message="checkCustom">please check custom value</span>
</div>

这样的事情可能吗?

谢谢

最佳答案

A form's controller有一个方便的属性叫做 $error。这是一个对象散列,包含对验证器失败的控件或表单的引用,其中它的键是错误名称(例如,emailrequiredminlength 等),它们的值是控件或表单的数组,这些控件或表单对于给定的错误名称具有失败的验证器 - source .

这意味着我们可以全局检查表单中的错误,只需检查此$error 对象是否包含特定键名 .

看看这个例子:

angular.module('myApp', ['ngMessages']);
[ng-cloak] {
display: none !important;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">

<div ng-app="myApp" ng-cloak>
<form name="myForm">
<div class="form-group">
<h3>Validation messages:</h3>

<div ng-messages="myForm.$error" multiple>
<div ng-message="required" class="alert alert-danger">There's at least one <strong>required</strong> field</div>
<div ng-message="minlength" class="alert alert-danger">There's at least one field which doesn't fulfill the <strong>minlength</strong> condition</div>
<div ng-message="email" class="alert alert-danger">The form contains an invalid <strong>email</strong> input</div>
</div>
</div>
<div class="form-group">
<label>Required Input 1</label>
<input type="text" ng-model="myModel1" required>
</div>
<div class="form-group">
<label>Required Input 2</label>
<input type="text" ng-model="myModel2" required>
</div>
<div class="form-group">
<label>Required Input 3 which has min-length="3"</label>
<input type="text" ng-model="myModel3" required ng-minlength="3">
</div>
<div class="form-group">
<label>Required Input 4 which is type="email"</label>
<input type="email" ng-model="myModel4" required>
</div>
</form>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.3/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.3/angular-messages.min.js"></script>

关于angularjs - Angular - ng-messages 中的多个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36376129/

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