在我的表单中,我想在用户关注表单控件时将其设置为不受影响,以便隐藏在触摸字段且字段无效时显示的验证消息。
我怎样才能做到这一点?
我曾尝试编写指令但无法使其发挥作用。我可以在控制台中看到指令中的值从 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);
});
}
};
});
Plunker http://plnkr.co/edit/oy9YNyaRzh13XHghIUk9?p=preview
尝试使用required 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
});
}
};
});
Plunker http://plnkr.co/edit/An6qCrc9Nt4itTeDqv9K?p=preview
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)