In this plunk的目标是根据控制器(而不是内置的required
或min-length
)中的验证显示错误消息。设置ng- message -exp时,不显示消息错误。
有没有关于如何让它工作,或者更好的ng-message
实际工作方式的想法,这与错误或模型有关?
HTML
<body ng-app="ngMessagesExample" ng-controller="ctl">
<form name="myForm" novalidate ng-submit="submitForm(myForm)">
<label>
This field is only valid when 'aaa' is entered
<input type="text"
ng-model="data.field1"
name="field1" />
</label>
<div ng-messages="myForm.field1.$error" style="color:red">
<div ng-message-exp="validationError">this is the error</div>
</div>
<br/><br/>
<button style="float:left" type="submit">Submit</button>
</form>
Javascript
var app = angular.module('ngMessagesExample', ['ngMessages']);
app.controller('ctl', function ($scope) {
$scope.submitForm = function(form) {
if (form.field1.$modelValue != 'aaa') {
$scope.validationError = true;
console.log('show error');
}
else {
$scope.validationError = false;
console.log('don\'t show error');
}
};
});
发布于 2016-02-15 13:12:01
您的主要ng-messages
参数与myForm.field1.$error
绑定在一起,但实际上您从未向form.field1.$error
中添加错误。因此,在控制器中,只需通过$setValidity(field, isValid)
向$error
对象手动添加一个错误
if ($scope.data.field1 != 'aaa') {
form.field1.$setValidity('validationError', false);
// Angular will make form.field1.$error.validationError = true;
}
else {
form.field1.$setValidity('validationError', true);
// Angular will make form.field1.$error.validationError = false;
}
然后,您就可以让ng-message
指令来完成它的工作。提供ng-message
的子元素已经被评估为其父ng-messages
的属性(请注意额外的s
)。因此,通常使用父元素作为表单元素的$error
对象,内部的子元素是属性,如$error.required
或在本例中为$error.validationError
。这里不需要ng-message-exp
:
<div ng-messages="myForm.field1.$error" style="color:red">
<div ng-message="validationError">this is the error</div>
</div>
发布于 2016-10-04 17:40:40
在控制器中执行此操作更合适的方法是使用$setValidity
if(a !== b){
form.inputName.$setValidity('custom-err', false);
} else {
form.inputName.$setValidity('custom-err', true);
}
form.$setSubmitted();
发布于 2017-04-04 23:46:59
Dmitry K的回答是非常好的。
我将扩展这个答案。
//Function before show your form:
vm.showForm(form){
form.$setPristine();
form.$setUntouched();
form.myFieldName.$setValidity('myCustomValidationName', false);
//More code...
}
//funtion to validate field on "ng-change"
vm.validateField(form){
if(xxxx == yyy) //Make your own validation{
form.myFieldName.$setValidity('myCustomValidationName', true);
}else{
form.myFieldName.$setValidity('myCustomValidationName', false);
}
}
以及相关的HTML代码:
<form name="myFormName" novalidate>
<md-input-container class="md-block">
<label>myField</label>
<input ng-model="ctrl.myFieldName" name="myFieldName" ng-change="ctrl.validateField(myFormName)" />
<div ng-show="myFormName.myFieldName.$touched || myFormName.$submitted">
<div ng-messages="myFormName.myFieldName.$error">
<div ng-message="myCustomValidationName">this is the message to show</div>
</div>
</div>
</md-input-container>
</form>
https://stackoverflow.com/questions/35401663
复制相似问题