gpt4 book ai didi

angularjs - ng-message 如何连接到模型,以及如何使用 ng-message 显示消息?

转载 作者:行者123 更新时间:2023-12-03 21:00:54 25 4
gpt4 key购买 nike

In this plunk目标是根据 Controller 中的验证显示错误消息(而不是内置的 requiredmin-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');
}
};


});

最佳答案

您的主 ng-messages参数与 myForm.field1.$error 有关,但您实际上从未向 form.field1.$error 添加错误.因此,在您的 Controller 中,只需手动将错误添加到 $error对象通过 $setValidity(field, isValid) :

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 的父一起使用。 object 和内部 child 是类似 $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>

Fixed plunker

关于angularjs - ng-message 如何连接到模型,以及如何使用 ng-message 显示消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35401663/

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