In order to register custom validation methods for custom form elements, we use extra directives as shown below:
<ng-form name="validatorTestForm">
<our-input-directive name="validatorTest"
ng-model="ourModel"/>
</our-input-directive>
<our-validator-directive name="validatorTest"
form="validatorTestForm"
ng-model="ourModel">
</our-validator-directive>
</ng-form>
These directives receive information through attributes specifying the input and form to validate. The connection is established by initializing the directive using a stripped-down version like this:
registerValidator(ourModel.form, 'validatorTest');
function registerValidator(form, inputName) {
var validationModel = form[inputName];
validationModel.$validators.testValidator = function (modelValue) {
// Validate to true when more than two characters are entered
return modelValue.length > 2;
};
}
The our-input-directive is straightforward:
angular.directive('ourInputDirective', function() {
return {
restrict: 'E',
template: '<input type="text" ng-model="model">',
scope: {
model: '=?ngModel'
}
}
});
Upon running the code, Angular appends numerous CSS classes to the form and input elements. When something is entered into the input field, the validation is triggered correctly. The form element is assigned the 'ng-valid' class if valid, and 'ng-invalid' if not.
However, the input only receives the 'ng-valid' class and never changes to invalid.
Why does this happen and how can we make it reflect the model changes on the input's CSS classes?
We aim to utilize the 'ng-invalid' class to style the input accordingly.