After using AngularJS for quite some time, I decided to explore Typescript. I managed to convert most of my Angular code to Typescript and found it beneficial, especially when working with services. However, I am struggling to convert the following directive to a Typescript class. It functions perfectly fine as AngularCode, but I'm looking for ways to make it work in Typescript.
angular.module('myValidation', [])
.directive('myValidation', function() {
return {
restrict: 'A',
require: "ngModel",
link: function(scope, elm, attrs, ctrl) {
switch (attrs.myValidation) {
case 'email':
var regex = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
break;
}
ctrl.$parsers.unshift(function(viewValue) {
if (regex.test(viewValue)) {
ctrl.$setValidity('myValidation', true);
}
else {
ctrl.$setValidity('myValidation', false);
}
return viewValue;
});
ctrl.$formatters.unshift(function(viewValue) {
if (regex.test(viewValue)) {
ctrl.$setValidity('myValidation', true);
}
else {
ctrl.$setValidity('myValidation', false);
}
return viewValue;
});
}
};
});