使用AngularJS将表单控件设置为不受影响

时间:2015-05-21 06:17:16

标签: 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

3 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:6)

当控件通过向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>

此外,您可能会认为控件的名称比&#34; name&#34;。

更好

答案 2 :(得分:2)

您只需要应用范围更改,因为validationApp.directive('untouch', function() { return { restrict: 'A', require: 'ngModel', scope: { untouch: '=' }, link: function(scope, element) { element.bind('focus', function() { scope.untouch.$setUntouched(); scope.$apply(); }); } }; }); 不会自行触发摘要:

JobLauncher

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