Set form control to pristine focus using AngularJS

In my form, I would like to set the form controls as untouched when the user focuses on them, to hide the validation messages that appear when the field is touched and invalid.

How can i do this?

I tried to write a directive, but could not get it to work. I see in the console that the value in the directive changes from true to false, but the form control is not updated.

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

+4
source share
3 answers

Try using the required controller 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

+8
source

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

, , "".

+6

You just need to apply the scope changes because you element.bindwon’t start the digest yourself:

validationApp.directive('untouch', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        scope: {
            untouch: '='
        },
        link: function(scope, element) {
            element.bind('focus', function() {
                scope.untouch.$setUntouched();
                scope.$apply();
            });
        }
    };
});

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

+2
source

Source: https://habr.com/ru/post/1589137/


All Articles