使用 AngularJS 将表单控件设置为未触及焦点 [英] Set form control to untouched on focus using AngularJS

查看:32
本文介绍了使用 AngularJS 将表单控件设置为未触及焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的表单中,当用户关注表单控件时,我想将表单控件设置为未触碰,以隐藏当字段被触碰且无效时显示的验证消息.

我该怎么做?

我曾尝试编写指令,但无法让它发挥作用.我可以在控制台中看到指令中的值正在从 true 更改为 false 但表单控件没有更新.

HTML:

<div class="form-group"><label>姓名*</label><input type="text" name="name" class="form-control" ng-model="user.name" untouch="userForm.name"/><h3>触摸:{{userForm.name.$touched}}</h3>

</表单>

指令:

validationApp.directive('untouch', function() {返回 {限制:'A',要求:'ngModel',范围: {触摸:'='},链接:函数(范围,元素){element.bind('焦点', function() {console.log(scope.untouch.$touched);scope.untouch.$setUntouched();console.log(scope.untouch.$touched);});}};});

Plunker

解决方案

尝试使用 required ngModel 控制器

.directive('untouch', function() {返回 {限制:'A',要求:'ngModel',链接:功能(范围,元素,属性,模型Ctrl){element.on('焦点', function() {modelCtrl.$setUntouched();范围.$应用();//请注意,dfsq 首先指出了这一点});}};});

Plunker

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

这篇关于使用 AngularJS 将表单控件设置为未触及焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆