I am using AngularJS and had been so for quite a while recently i started to mess around with Typescript i was able to convert most of my Angular code to Typescript and found great benefit especially when it get to services, but i can not convert the following directive to typescript class anyone has an idea how to do that, it works perfectly fine as AngularCode
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;
});
}
};
});
directiveandfactoryshouldn't be converted into typescript classes, IMO. Directives specifically should be functions returningng.IDirective. Check my answer to this questionservice-function andcontroller-function is called with new it fits good to just provide the class.factory-function anddirective-function is however not called with new so you have to do it manually if you use class. Normally if you want to use a class with a service you should useserviceinstead offactory, but since thedirective-function is a factory function that is not called with new, using it as a function fits better