How to force a check to run a model when changing another model?

I have an input field with the number $validators registered on it, which updates the model. Some of these validators are compared with other field values ​​(which are also updated with input fields).

How to get AngularJS to run these checks again when changing other values ​​it depends on?

I tried to find something related to this in the documentation, and also created $watch in a dependent field and simply set the model value for myself (hoping that this would lead to re-certification), but no luck with any of them.

+6
source share
2 answers

If you are using Angularjs 1.3+, you can use the $ validate method. Suppose your input "A" is one that depends on other inputs, lets call them "B". You can add a function to each of the B $ viewChangeListeners, which simply calls the A $ validation method. This will have the following effect; every time you change one of the B inputs, your A input validators are triggered.

+5
source

I know that this was given some time ago, but I had a similar problem, and I managed to assemble a suitable solution from many other answers and some trial and error. I suppose someone else might find something similar one day ...

Here is a method that (as far as I can tell) is directly related to the validation system. In this particular example, a match validation rule is created that compares two models and checks to see if their value matches.

 <script type="text/javascript"> angular.module( "YourModule", [] ) .directive( "match", function() { return { require: 'ngModel', restrict: 'A', link: function( $scope, $elem, $attrs, $ctrl ) { // targetModel is the name of the model you want to // compare against. var targetModel = $attrs.match; // Add the 'match' validation method $ctrl.$validators.match = function( modelValue, viewValue ) { valid = $scope.$eval( targetModel ) == viewValue; $ctrl.$setValidity( 'match', valid ); return valid ? viewValue : undefined; }; // When the target model value changes, cause this model // to revalidate $scope.$watch( targetModel, function() { $ctrl.$validate(); } ); } }; } ); 

Then use this (obviously including form, ng-app and ng-controller ):

 <input type="password" ng-model="password" /> <input type="password" ng-model="confirmation" match="password" /> 

The general idea is that when processing the correspondence directive, an additional function ( match ) is added to the $validators of the $ctrl object, where other validators (mandatory field, minimum length, ...) seem to live. This sets the check in the field, but this rule is only processed when updating the field with the compliance directive.

To combat this, the clock is then set on the target model. When the value of the target model is updated, it will run the $validate() method in the original control, allowing you to check the validity in either of the two fields.

+3
source

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


All Articles