使用AngularJS将窗体控件设置为未触及的焦点

Set form control to untouched on focus using AngularJS

本文关键字:焦点 设置 AngularJS 窗体 控件 使用      更新时间:2023-09-26

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

我该怎么做?

我试过写一个指令,但一直无法让它工作。我可以在控制台中看到指令中的值从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控制器

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

恰好

当控件获得焦点时,您可以通过向html添加一个属性来轻松地保持控件不变-不需要新的指令。只需添加

ng-focus="userForm.name.$setUntouched()"

<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>

另外,您可以考虑为控件取一个比"name"更好的名字。

您只需要应用范围更改,因为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();
            });
        }
    };
});
演示:

http://plnkr.co/edit/fgtpi7ecA34VdxZjoaZQ?p=preview