Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set form control to untouched on focus using 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.

How can I do this?

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>

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

like image 584
Jaydo Avatar asked Dec 02 '22 17:12

Jaydo


1 Answers

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

like image 133
Phil Avatar answered Dec 05 '22 06:12

Phil