How to retrieve Angular directive name using TypeScript

I have successfully implemented the following AngularJS directive:

export module Directives {

    export class PasswordsMatch implements ng.IDirective {

        public static Factory(name: string) : ng.IDirectiveFactory {
            return () => new PasswordsMatch();
        }

        require = 'ngModel';            
        link = (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: Attributes): void => {
            // wondering how to retrieve the directive name here?
        };
    }
}

This directive is then registered in another script file as:

class Application {
    private app: ng.IModule;

    constructor() {     

        // Controllers

        // Directives           
        this.app.directive('ngPasswordsMatch', Directives.PasswordsMatch.Factory());
    }        
}

Is there a way to access the directive name inside the link function without having to pass it to the Factory function again (so as to avoid duplication of directive names)?

Answer №1

To enhance accessibility, consider storing the directive name in a variable that can be accessed from anywhere within the code.

let directiveName = 'ngPasswordsMatch'; //declare directive name as a string
export module Directives {

  export class PasswordsMatch implements ng.IDirective {

    public static Factory(name: string): ng.IDirectiveFactory {
      return () => new PasswordsMatch();
    }

    require: 'ngModel';
    link = (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: Attributes): void => {
      console.log(directiveName); //access directive name here
    };
  }
}

this.app.directive(directiveName, Directives.PasswordsMatch.Factory());

By using this approach, the directiveName variable provides easy access to the directive name.

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

What prevents `console.log` from working within a button click event?

Why is this not functioning correctly? <button (click)="console.log('ok');">Display Details</button> The error message reads: Cannot read property 'log' of undefined However, a console.log statement in the class construc ...

Tips on making a forced call to `super.ngOnDestroy`

I am utilizing an abstract class to prevent redundant code for unsubscribing observables. Here is what it looks like: export abstract class SubscriptionManagmentDirective implements OnDestroy { componetDestroyed = new Subject<void>() constructor ...

Why isn't the jQuery function being triggered from an Angular callback?

Here is the code snippet that I am currently working with: $http({method: 'GET', url: 'api/participants/areyouhuman'}) .success(function(data, status, headers, config) { console.log(data); $( ...

Attempting to retrieve data either by code or with a WHERE condition proves unsuccessful as the data retrieval process yields no results

Seeking assistance with my Angular project that is utilizing a Node.js server and MSSQL express. I am having trouble retrieving data using a WHERE condition in my code. Any help in identifying the missing piece or error would be appreciated. Thank you. // ...

Building on the functionality of AngularJS, a directive scope can be established to access and modify

Can a directive accept and utilize a parameter as its scope value? For instance: angular .module('app', []) .controller('CTRL', function($scope) { $scope.some_value = { instance1: { key1: 'value11', ...

Please provide either a string or an object containing the proper key for TypeScript

Within my project, the languageSchema variable can either be a string or an object containing the 'Etc' key. The corresponding interface is defined as follows: let getLanguageSchema = (language: string): string => languagesSchemas[language]; ...

NestJS testing issue encountered: Compiled JS file not found in E2E test using Mocha

I'm currently facing an issue with executing an E2E test. The file structure for the E2E test is auto-generated by nestcli. import { Test, TestingModule } from '@nestjs/testing'; import { INestApplication } from '@nestjs/common'; i ...

The interfaces being used in the Redux store reducers are not properly implemented

My Redux store has been set up with 2 distinct "Slice" components. The first one is the appSlice: appSlice.ts import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import type { RootState } from "./store"; export interface CounterState { value ...

Solving automatically generated TypeScript MongoDB types for GraphQL results

Utilizing the typescript-mongodb plugin along with graphql-codegen to automatically generate Typescript types enables easy data retrieval from MongoDB and GraphQL output via Node. The initial input schema in GraphQL format appears as follows: type User @ ...

Type of event target MouseEvent

I am currently working on a custom hook const hasIgnoredClass = (element: Element, ignoredClass: string) => (element.correspondingElement ? element.correspondingElement : element ).classList.contains(ignoredClass); const isInIgnoredElement = ( ...

How can you pre-load SVG images in an Ionic view?

After developing a mobile app using Ionic, I encountered a slow loading time for one specific view that includes a large SVG image of 202KB. The delay in loading the view/page can be frustrating as it takes around 3-4 seconds to fully load and display. Is ...

Typescript: Subscribed information mysteriously disappeared

[ Voting to avoid putting everything inside ngOnit because I need to reuse the API response and model array in multiple functions. Need a way to reuse without cluttering up ngOnInit. I could simply call subscribe repeatedly in each function to solve the p ...

Is it possible for an uninitialized field of a non-null literal string type to remain undefined even with strict null checks in

It seems that there might be a bug in Typescript regarding the behavior described below. I have submitted an issue on GitHub to address this problem, and you can find it at this link. The code example provided in that issue explains the situation more clea ...

`Managing select tag data in Angular reactive forms`

Having an issue with selecting the gender option from JSON formatted data received from the backend. The gender is displayed as a select tag on the frontend, but it does not pre-select the option that corresponds to the gender value in the JSON data. The b ...

Trigger .gif on hover using ng-repeat in AngularJS

Many solutions to this problem involve using jQuery, such as the following examples: Stop a gif animation onload, on mouseover start the activation and Animating a gif on hover. However, I'm interested in achieving the same functionality using Angular ...

The function useNuxtApp() in Nuxt 3 is returning an unknown type

I have been working on creating a helper that can be used across all composables and applications in my Nuxt plugin. Here is how the code looks: // hello.ts export default defineNuxtPlugin(async nuxtApp => { nuxtApp.vueApp.provide('hello', ...

Issue with Readonly modifier not functioning as expected in Angular/Typescript

My goal is to create a component property that is read-only. However, I am facing an issue where the readonly modifier does not seem to have any effect. View example on stackblitz According to the documentation, once I initialize the cars property in the ...

Alternative for document.ready in AngularJS when outside of AngularJS

I am currently developing a small Chrome extension that will interact with an Angular website. I have managed to successfully detect full page reloads using $(document).ready(), but I am facing issues when it comes to detecting page changes triggered by ng ...

Possibility for Automatic Type Inference in Generics

Is there a way to have a method infer the type of function parameter without specifying its generic? Currently it is 'GET' | 'POST', but I only need the literal 'GET' const func = <Params, Method extends "GET" | & ...

Issue with SVG on tainted canvas causes IE security error when using toDataURL

In my Angular JS directive, I have implemented a feature to export SVGs to PNG. While this functionality works seamlessly in most browsers, it encounters a security error in IE. Despite my numerous attempts to troubleshoot the issue, I have been unable to ...