我有一个带有一些输入的表单,这些输入在md-input-container中。每个输入都有一些带有ng-messages指令的验证消息:
<form name="ctrl.myForm" layout="column" ng-submit="addUser(model)">
<input hide type="submit" />
<div layout="column" layout-padding>
<md-input-container>
<label translate>Username</label>
<input name="username" ng-model="model.username" type="text" required>
<div ng-messages="ctrl.myForm.username.$error">
<div ng-message="required" translate>This field is required.</div>
<div ng-message="unique" translate>Username is used before.</div>
</div>
</md-input-container>
<md-input-container>
<label translate>Email</label>
<input name="email" ng-model="model.email" required>
<div ng-messages="ctrl.myForm.email.$error">
<div ng-message="required" translate>This field is required.</div>
<div ng-message="email" translate>Email is not valid.</div>
</div>
</md-input-container>
</div>
<div layout="row">
<span flex></span>
<md-button
class="md-raised"
ng-click="cancel()">
<wb-icon>close</wb-icon>
<span translate>Cancel</span>
</md-button>
<md-button
class="md-raised"
ng-click="addUser(model)">
<wb-icon>done</wb-icon>
<span translate>Add</span>
</md-button>
</div>
</form>
在我的控制器中,我有一个名为addUser(model)的函数,该函数将给定数据发送到服务器并接收一些验证代码。我在$ error对象中设置了适当的键,但未显示相关消息。如果从服务器收到错误,我将密钥设置如下:
function addUser(model){
$myService.newUser(model)//
.then(function(user) {
// user is created successfully.
}, function(error) {
ctrl.myForm.$invalid = true;
ctrl.myForm.username.$error['unique'] = true;
ctrl.myForm.email.$error['email'] = true;
});
}
我希望将键设置为true时,相关消息会显示在表单中,但消息不会显示。此时,如果我更改与该字段相关的消息的值,则会显示该字段!我找不到问题。
答案 0 :(得分:0)
在<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1> Welcone to the booking site </h1>
<h4> Please, choose a destination </h4>
<form name="myTravelForm">
<label> First name: </label><br>
<input type="text" name="firstname" id="firstname"/><br>
<br>
<select name="destination">
<option value="Antarctica" selected>Antarctica</option>
<option value="Costa Rica">Costa Rica</option>
</select>
<input type="button" value="Add this destination" id="banana"/>
</form>
<div id="travelerInfo"></div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
处读到有关https://docs.angularjs.org/guide/forms
的内容,也有一些示例。 ({$asyncValidators
等)
简而言之:
Angularjs内置验证要求您编写和添加验证器。您不应该手动控制ctrl.$asyncValidators.username=...
字段(这就是为什么它们有$前缀)的原因。
Angularjs资料也遵循这种方法。
P.S。 $invalid, $error
之类的行无法连续工作的原因很简单-angularjs下一次验证运行会将其设置为false