In AngularJS, how to force a re-validation of a field in a form when another value in the same form changes?

I have a form with several fields, however the selection and input fields are connected: the input check depends on what value the user selects in the selection field.

I will try to clarify an example. Let's say that select contains the names of the planets:

<select id="planet" class="form-control" name="planet" ng-model="planet" ng-options="c.val as c.label for c in planets"></select> 

at the input, I apply custom validation using a custom directive called "input-validation":

 <input id="city" input-validation iv-allow-if="planet==='earth'" class="form-control" name="city" ng-model="city" required> 

where is the directive:

 .directive('inputValidation', [function() { return { require: 'ngModel', restrict: 'A', scope: { ivAllowIf: '=' }, link: function(scope, elm, attrs, ctrl) { ctrl.$parsers.unshift(function(viewValue) { //input is allowed if the attribute is not present or the expression evaluates to true var inputAllowed = attrs.ivAllowIf === undefined || scope.$parent.$eval(attrs.ivAllowIf); if (inputAllowed) { ctrl.$setValidity('iv', true); return viewValue; } else { ctrl.$setValidity('iv', false); return undefined; } }); } }; }]) 

A full example can be viewed in Plnkr: http://plnkr.co/edit/t2xMPy1ehVFA5KNEDfrf?p=preview

Whenever the selection changes, I need to enter the confirmation again. This does not happen in my code. What am I doing wrong?

+4
source share
1 answer

I did the same to check the start date of the change to the end date. In the start date directive, add hours to change the end date and then call ngModel.$validate() if a new end date value is defined.

  scope.$watch(function () { return $parse(attrs.endDate)(scope); }, function () { ngModel.$validate(); }); 

The important part to call is the call to ngModel.$validate() inside the directive.

Note you must use the $ validators for the special checks above to work. read here , $ parsers - old way - from angularjs 1.3 use $ validators

FIXED PLANKER LINE

+5
source

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


All Articles