Note that there are some explanatory texts on larger screens.

plurals
  1. POAngular JS $watch priority over ng-change
    text
    copied!<p>I am making a registration form using Angular JS where a function, <code>regisChange()</code>, is executed through <code>ng-change</code>.</p> <p>I have another custom-made directive called <code>equals</code> that uses <code>$watch</code> to check the password fields and uses <code>ngModel.$setValidity('equals', password1==password2)</code> to set the validity of the form.</p> <p>Ideally, whenever a user changes his password field, I would want the <code>equals</code> directive to be executed before <code>ng-change</code>. This is so that the <code>equals</code> can set the validity of the form before the <code>ng-change</code> refers to it.</p> <p>The question is how do I execute a <code>$watch</code> on the change of input before the function in <code>ng-change</code>?</p> <p><strong>HTML</strong></p> <pre><code> &lt;div class="form-group"&gt; &lt;label for="register-password1"&gt;Password&lt;/label&gt; &lt;input name="password1" type="password" class="form-control" ng-model="user.password1" required ng-minlength="6" ng-maxlength="20" equals="{{user.password2}}" ng-blur="fieldValidate('password1')" ng-change="regisChange('password1')"&gt; &lt;div class="error"&gt;{{error.password1}}&lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="register-password2"&gt;Confirm Password&lt;/label&gt; &lt;input name="password2" type="password" class="form-control" ng-model="user.password2" required equals="{{user.password1}}" ng-blur="fieldValidate('password2')" ng-change="regisChange('password2')"&gt; &lt;div class="error"&gt;{{error.password2}}&lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>Equals Directive</strong></p> <pre><code>welcome.directive('equals', [function(){ return { restrict: 'A', // only activate on element attribute require: 'ngModel', // get a hold of NgModelController link: function(scope, elem, attrs, ngModel) { if(!ngModel) return; // do nothing if no ng-model // watch own value and re-validate on change scope.$watch(attrs.ngModel, function() { validate(); }); // observe the other value and re-validate on change attrs.$observe('equals', function (val) { validate(); }); var validate = function() { // values var val1 = ngModel.$viewValue; var val2 = attrs.equals; // set validity console.log('val1: '+val1) console.log('val2: '+val2) ngModel.$setValidity('equals', val1 === val2); }; } } }]); </code></pre> <p><strong>regisChange() in the Controller</strong></p> <pre><code>$scope.regisChange = function(fieldName){ console.log($scope.regisForm["password2"].$valid); if($scope.regisForm[fieldName].$valid){ $scope.error[fieldName] = ""; } }; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload