问题
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
回答1:
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
回答2:
You can make the control untouched easily when the control gains focus by adding one attribute to the html - no new directives required. Simply add
ng-focus="userForm.name.$setUntouched()"
and you have
<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"
ng-focus="userForm.name.$setUntouched()" />
<h3>Touched: {{userForm.name.$touched}}</h3>
</div>
</form>
Also, you might consider a better name for your control than "name".
回答3:
You just need to apply scope changes, because element.bind
won't trigger digest by itself:
validationApp.directive('untouch', function() {
return {
restrict: 'A',
require: 'ngModel',
scope: {
untouch: '='
},
link: function(scope, element) {
element.bind('focus', function() {
scope.untouch.$setUntouched();
scope.$apply();
});
}
};
});
Demo: http://plnkr.co/edit/fgtpi7ecA34VdxZjoaZQ?p=preview
来源:https://stackoverflow.com/questions/30365914/set-form-control-to-untouched-on-focus-using-angularjs