在我的表单中,当用户关注表单控件时,我想将其设置为未触及,以便隐藏当字段被触摸且无效时显示的验证消息。
我该怎么做?
我曾尝试编写一个指令,但无法让它工作。我可以在控制台中看到指令中的值从 true 变为 false,但表单控件没有更新。
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>
指令:
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);
});
}
};
});
最佳答案
尝试使用必需的 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
});
}
};
});
关于javascript - 使用 AngularJS 将表单控件设置为未触及焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30365914/