In my form, I would like to set form controls as untouched when the user focuses on them in order to hide the validation messages which are displayed when the field is touched and invalid.
How can I do this?
I have tried writing a directive but have been unable to get it to work. I can see in the console that the value in the directive is changing from true to false but the form control doesn't update.
HTML:
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate="">
<div class="form-group">
<label>Name*</label>
<input type="text" name="name" class="form-control" ng-model="user.name" untouch="userForm.name" />
<h3>Touched: {{userForm.name.$touched}}</h3>
</div>
</form>
Directive:
validationApp.directive('untouch', function() {
return {
restrict : 'A',
require: 'ngModel',
scope: {
untouch : '='
},
link: function(scope, element) {
element.bind('focus', function() {
console.log(scope.untouch.$touched);
scope.untouch.$setUntouched();
console.log(scope.untouch.$touched);
});
}
};
});
Plunker
Try using the required ngModel
controller
.directive('untouch', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, modelCtrl) {
element.on('focus', function() {
modelCtrl.$setUntouched();
scope.$apply(); // just note, dfsq pointed this out first
});
}
};
});
Plunker
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With