Validating Matching Text using an Angular Directive

This is a nice angular directive I found which can be used with AngularJS validation to make sure the text in two inputs match. The most common scenario for this would be for a form where a user must create a new password.

The directive:

.directive('compareText', [function () {
        return {
            require: 'ngModel',
            link: function (scope, elem, attrs, ctrl) {
                var firstTextBox = '#' + attrs.compareText;
                elem.add(firstTextBox).on('keyup', function () {
                    scope.$apply(function () {
                        var v = elem.val() === $(firstTextBox).val();
                        ctrl.$setValidity('textMatch', v);
                    });
                });
            }
        }
    }])

Implementation:

<form name="myForm">
   <input id="pw1" type="password" placeholder="* Password" name="password1" ng-model="model.Password1">
   <input id="pw2" type="password" placeholder="* Repeat Password" name="password2" compare-Text="pw1" ng-model="model.Password2">
   <div ng-show="myForm.password2.$error.textMatch">Must match Password</div>
</form>

 

This is a very simple and reusable directive that makes sure that the text in the inputs match using some jQuery.