javascript - 使用 AngularJS 将表单控件设置为未触及焦点

标签 javascript angularjs forms angularjs-directive

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

我该怎么做?

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

最佳答案

尝试使用必需的 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

关于javascript - 使用 AngularJS 将表单控件设置为未触及焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30365914/

相关文章:

javascript - 将图像作为正文附加到 golang 服务器的 POST 请求中

javascript - 通过带 Angular 滚动来移动元素

javascript - 有没有办法用 JavaScript 隐藏表单的各个部分?

javascript - 异常 : Cannot find a differ supporting object 'storeApps' in [apps in AppWidgetsComponent@8:28]

javascript - 通过 Struts 2 操作类从数据库填充下拉列表(使用 jtable)

javascript - 单击图像时,Jquery悬停图像出现问题

javascript - 我应该在 AngularJS 中使用关联数组吗?

javascript - 如果用户在 angularjs 中不活动,如何在给定时间后自动重新加载页面

html - 即使 reCaptcha 已完成,提交按钮也会发送电子邮件

php - 如何在 laravel 的编辑表单中获取可选值