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

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

问题描述

在我的表单中,我想将表单控件设置为当用户将其重点放在用户面前时保持不变,以便隐藏在触摸该字段时显示的验证消息,并且该消息无效.

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.

我该怎么做?

我尝试编写指令,但无法使其正常工作.我可以在控制台中看到指令中的值从true更改为false,但是表单控件没有更新.

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>

指令:

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控制器

.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
            });
        }
    };
});

柱塞

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

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