I've struggled with this, and it's messy. I see no help in a directive, because logically, all that's needed is to constrain one value to match another by validation. All I needed was ng-pattern
and a helper filter to escape a string into a tight regular expression. (Note I'm checking emails, but the concept is identical.)
My code:
<input type="email" name="email" ng-model="data.email"
required placeholder="jane.doe@example.com">
<input type="email" name="verify" ng-model="verify"
required ng-pattern="data.email | quotepattern">
The quotepattern
filter implementation is:
function(input) {
if (!! input) {
return "^" + input.replace(/(\W)/g, "\\$1") + "$";
} else {
return input;
}
}
This does a valid binding on both, and checks for validity. If the first value changes, both controls get updated. If the verify control value changes, only that control is affected.
To me, this is infinitely simpler than directive hackery, and conceptually more correct too, since logically all you need to do is check for a string match in the verify control. Engineering an entire new control with custom editing logic to do that is breeding an entire yak only to shave it.