javascript 使用 AngularJS 将表单控件设置为未触及焦点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30365914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set form control to untouched on focus using AngularJS
提问by Jaydo
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.
我曾尝试编写指令,但无法让它发挥作用。我可以在控制台中看到指令中的值正在从 true 更改为 false 但表单控件没有更新。
HTML:
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);
});
}
};
});
回答by Phil
Try using the requiredngModel
controller
尝试使用所需的ngModel
控制器
.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
});
}
};
});
回答by steampowered
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
通过向 html 添加一个属性,您可以在控件获得焦点时轻松地使控件保持不变 - 不需要新的指令。只需添加
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".
此外,您可能会为您的控件考虑一个比“名称”更好的名称。
回答by dfsq
You just need to apply scope changes, because element.bind
won't trigger digest by itself:
您只需要应用范围更改,因为element.bind
它本身不会触发摘要:
validationApp.directive('untouch', function() {
return {
restrict: 'A',
require: 'ngModel',
scope: {
untouch: '='
},
link: function(scope, element) {
element.bind('focus', function() {
scope.untouch.$setUntouched();
scope.$apply();
});
}
};
});