2

Consider this runnable example: http://plnkr.co/edit/1BfO7KkHeMD3EpsULNGP?p=preview

<html ng-app='app'>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.4/angular.js"></script>
<script>
angular.module('app', [])
.directive('pwCheck', [function () {
  return {
    require: 'ngModel',
    link: function (scope, elem, attrs, ctrl) {
      var firstPassword = '#' + attrs.pwCheck; 
      elem.add(firstPassword).on('keyup', function () { 
          var v = elem.val()===$(firstPassword).val();
          console.log(v);
          ctrl.$setValidity('pwcheck', v); 
      });
    }
  }
}]);
</script> 
<form name="form">
<input type="text" id="pw1" name="pw1" ng-model="pw1Model">
<input type="text" name="pw2" pw-check="pw1" ng-model="pw2Model">
Valid:  {{form.pw2.$valid}}
<pre>{{form.pw2 |json}}</pre>
</form>

Write a character i one of the fields, and see that the validity is not updated until the second character is written in. The validity is not correct if you test to copy/paste etc. But the correct value v is logged. Why is the model not changed correctly?

1 Answer 1

1

Wrap $setValidity into $timeout

$timeout(function() {
   ctrl.$setValidity('pwcheck', v);
});

http://plnkr.co/edit/OSuHBgtReDoCGWi03Cc8?p=preview

I assume that there is some conflict with the $setValidity call of angular native input directive. Wrapping this call into $timeout makes it possible to avoid this conflict.

Sign up to request clarification or add additional context in comments.

2 Comments

Is it similar to nextTick()?
Yes. To be more exact $setValidity call will be queued.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.