Implementing a Typescript directive in AngularJS to create a class

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;
                });
            }
        };
    });    

Answer №1

https://github.com/uniqueurl-to-learn-more

@directive(app)
export default class CopyText implements IDirective {
    angularModule = app;
restrict = "E";

scope: any = {
    model: "="
};

templateUrl = "UniqueTemplates/Directives/copyText.html";

link: (scope: any, elm: any) => void = (scope, elm: any) => {
    var input: JQuery;

    scope.select = ($event) => {
        input = $($event.target).next().first();
    };
    scope.copy = () => {
        input.on("focus", function() {
            this.setSelectionRange(0, this.value.length);
        });

        input.focus();
    };
};

}

Answer №2

In order to use a directive with an AngularJS TypeScript class, you must create a Factory function that will return an instance of your class. Here's an example:

Module Directive{
 class myDirectiveCtrl {

        private name: string;
        private items: Array<string>;
        private $q: ng.IQService;
        static $inject = ['$scope','$window','$q'];

        constructor($scope: ImyDirectiveScope, $window) {
            this.name = $scope.name;
            this.items = ['salut', 'hello', 'hi', 'good morning'];
        }

        clickMe = ():void => {
            console.log('dssff');
            this.items.push('yo');
        }

    }
    export interface ImyDirectiveScope {
        name: string
    }

        export class myDirective implements ng.IDirective {
                 restrict = 'E';
                 template = '<div><h1>{{vm.name}}</h1><div ng-repeat="i track by $index in vm.items">{{i}}</div><hr/><button type="button" ng-click="vm.clickMe()">Click Me</button></div>';
                 replace = true;
                 scope = {
                     name: '@'
                 };
                 controller = myDirectiveCtrl;
                 controllerAs = 'vm';

                 link = (scope: ng.IScope, element: ng.IAugmentedJQuery, attributes: ng.IAttributes, controller: myDirectiveCtrl) => {

                 };

                 constructor() { };
                 static factory(): ng.IDirectiveFactory {
                     var directive = () => new myDirective();
                     return directive;
                 }

             }

    app.directive('myDirective',Directive.myDirective.factory());
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Traversing through nested states in ui-router without refreshing the parent state

In my current project, there are multiple organizations featured. Each organization page consists of two main sections: a header displaying organization information that should only load once, and a tabs zone for navigating different sections. I have imple ...

Attempting to compile TypeScript by referencing ng2-bootstrap using Gulp within Visual Studio

I've been struggling with this issue for a few days now, and I'm really hoping someone can help me out. Currently, I am experimenting with Angular2 in an aspnet core project. The setup involves using a gulpfile.js to build .ts files and transfer ...

What kind of null/undefined is being assumed?

system details: Visual Studio Code Version: 1.47.3 Typescript Version: 4.0.0-dev.20200727 tsconfig.js: "strict": true, code example: let x = null; // x is any type let y = x; // x is null type(why? x is any type on top), y is null type x = 1; / ...

Can a ng-repeat value be assigned to a text input field?

<tr ng-repeat="person in users" ng-class="{'chosen': person.AdmissionID == currentSelection}" ng-click="selectRow(person.AdmissionID)"> <td>{{person.AdmissionID}}</td> <td>{{person.AdmissionNumber}}</td> ...

Error: The AppModule encountered a NullInjectorError with resolve in a R3InjectorError

I encountered a strange error in my Angular project that seems to be related to the App Module. The error message does not provide a specific location in the code where it occurred. The exact error is as follows: ERROR Error: Uncaught (in promise): NullInj ...

PrimeNG Component Containing a Dynamic Dialog Instance

I am experiencing an issue with handling dynamic dialogs in PrimeNG. Is there a solution for managing actions on a dialog other than just using the close option? For instance, in the context of the Kendo-UI dialog example, I can specify the content.insta ...

Hover shows no response

I'm having trouble with my hover effect. I want an element to only be visible when hovered over, but it's not working as expected. I've considered replacing the i tag with an a, and have also tried using both display: none and display: bloc ...

Setting Angular FormControl value to null within a service

My Angular form is reactive and collects mobile numbers along with other details. Here is the code snippet: component.html <form [formGroup]="contactDetailsForm"> <ngx-intl-tel-input [cssClass]="'ngxIntlInputBorder'&quo ...

Issue with CORS when starting SAM local API

I have encountered a CORS issue while using AWS CDK (Typescript) and running SAM local start-api to launch an API connected to lambda resolvers. The problem arises when attempting to access the API from a web browser. Below is the code snippet causing the ...

Modifying Characteristics of Elements Added Dynamically

How do I change the type attribute for dynamically added buttons? In the code below, the label names are changing perfectly, but when I try to change button types, it applies to all dynamically added buttons. My requirement is to change every button type t ...

Issue navigating with Angular routes

I've been struggling with routing for the past couple of days without any success. I've gone through various questions on stackoverflow and tried implementing the solutions provided in the answers, but to no avail. I included the route script in ...

Angular JS integration for optimal Bootstrap grid alignment

Recently, I have been exploring the Bootstrap framework and experimenting with grid alignment. When working with 4 columns, W3 schools recommends using the following row setup: <div class="row"> <div class="col-lg-3"> </div> ...

Prevent duplicate components from interacting with one another in Angular

My Tabs component has its own variables and functions, and it works perfectly. However, I encountered an issue when trying to place multiple tab components on the same page. Whenever I change the value of one tab, it also affects the other tab component. ...

Query and display comments on posts using AngularJS and ng-repeat from a restful Api with model relations

After much consideration, I have chosen to utilize Restangular due to its compatibility with the Lodash library in AngularJS. However, I am facing a challenge with the getList() function as my server responses contain two parameters, only one of which is a ...

HTML page not being displayed in the AngularJS $routeProvider within the <div ng-view> tag

I'm a beginner in AngularJS and seeking assistance with resolving an issue related to routing to another HTML page while passing a parameter. My application consists of a form with input fields for name & course. The user's inputted information w ...

Using TypeScript to create a unique object type that is mapped with generics for each key

Suppose I have a type representing an array of two items: a list of parameters and a function with arguments corresponding to the parameters. I've created a handy function to infer the generic type for easy use. type MapParamsToFunction<A extends a ...

What is the process for importing string data into an Excel document using Angular?

I'm encountering a situation where I have non-JSON data coming from the backend. How can I efficiently write this type of data into an Excel file? To handle this task, I've utilized XLSX and FileSaver libraries by referencing an example on Plunk ...

What is the best way to access and interpret a JSON file within an Angular application?

I am facing difficulties while trying to load a JSON file from my local disk in order to populate a FabricJS canvas with the data. Currently, I am encountering issues retrieving the data from the file. Here is what I have attempted so far. app.html < ...

Version 4.0 of d3 introduces an import statement that provides a __moduleExports wrapper

Having difficulty with an import statement in my D3 4.0 and Ionic2/Angular2 project. I believe the import statement is correct, as everything compiles successfully. import * as d3Request from 'd3-request'; export class HomePage { construc ...

Display content exclusively in PDF format

On my HTML page, I have two sections - one for inputting values and the other for viewing a PDF. To ensure that the PDF view is hidden until explicitly requested, I need it to remain invisible by default. It should only appear as a PDF when someone clicks ...