Reputation: 828
I have a form with some inputs which are in md-input-container. Each input have some validation message with ng-messages directive:
<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>
In my controller, I have a function named addUser(model) which send given data to server and receives some validation codes. I set appropriate keys in $error objects but relative messages are not show. I set keys as following if I get error from server:
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;
});
}
I expect when I set keys as true related messages appear in the form but message are not shown. In this time if I change value of a field related message of that field is shown! I could not find problem.
Upvotes: 0
Views: 338
Reputation: 9486
Read here https://docs.angularjs.org/guide/forms
about $asyncValidators
, there are some examples also. (ctrl.$asyncValidators.username=...
etc.)
In few words:
Angularjs built-in validation requires you to write and add validators. You should not control $invalid, $error
fields manually (Thats why they have $ prefix).
Angularjs material also follow this approach.
P.S. reason why lines like ctrl.myForm.$invalid = true;
wont work consistently is quite simple - angularjs next validation run will set it back to false
Upvotes: 0