Angular TypeScript Directive Link function not being executed

I've been working on implementing a Role-Based-Access-Control system in my application. The allowed resources are loaded from the server after login, and I was able to verify this using raw JavaScript code.

angular.module('app').directive('accessControl',
[
    'AuthService', function (authService) {
        return {
            restrict: 'A',
            scope: "=",
            link: function (scope, element, attrs) {
                scope.canShow = function(resource) {
                    var allowedResources = authService.accountInfo.resources;
                    return allowedResources.indexOf(resource) !== -1;
                }

            }
        }
    }
]); 

However, as my entire application is in TypeScript, I have been attempting to create the directive in pure TypeScript without success. Here is my TypeScript code:

export class AccessControl implements ng.IDirective {

    public authService: App.AuthService;
    public link: (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => void;

    constructor(authService: App.AuthService) {
        this.authService = authService;
        console.log('authservice: ', authService);
        
        AccessControl.prototype.link = (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => {
            scope["canShow"] = function (resource: string) {
                // some logic
                console.log('can show' + resource);
                return true;
            };
        };
    }

    public static factory(): ng.IDirectiveFactory  {
        var directive = (authService: App.AuthService) => {
            return new AccessControl(authService);
        };

        directive['$inject'] = ['AuthService'];
        return directive;
    }

    restrict = "A";
    scope: "=";
}

angular.module('app').directive('accessControl', AccessControl.factory());

Unfortunately, it seems that the link function is never being called. Any help or guidance on this issue would be greatly appreciated.

Answer №1

In the past, we have typically defined the link as a public function within the class. In order to use an isolate scope, you would need a public scope variable on your directive class. Additionally, setting $inject directly on the directive is simpler than using bracket property notation. Below is an example of how we create directives using TypeScript:

namespace app.directives {
    export class AccessControl implements ng.IDirective {

        public restrict = "A";

        constructor(private authService: App.AuthService) {
            console.log("authservice: ", this.authService);
        }

        public link(scope: ng.IScope, 
                    element: ng.IAugmentedJQuery, 
                    attrs: ng.IAttributes) {
            console.log("in link function of directive", scope);
        }

        public static factory(): ng.IDirectiveFactory  {
            var directive = (authService: App.AuthService) => {
                return new AccessControl(authService);
            };

            directive.$inject = ["AuthService"];
            return directive;
        }
    }

    angular.module("app")
        .directive("accessControl", AccessControl.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

What are the conditionals and operations that need to be underscored in this template?

I am new to working with underscore and I need help writing an "each" function for posts where only the latest post is displayed. I understand the basic logic which looks like this <% _.each(posts, function(post, index) { %> <% if(index % 3 == 0 ...

Is it possible to showcase the data from three or more PHP files on a single webpage?

I currently have three PHP files: pie.php, bar.php, and line.php. When each file is run individually, it displays a webpage with a pie chart, bar chart, or line graph respectively. However, running all three files opens up separate webpages for each graph. ...

What is the best way to prevent useEffect from triggering when a modal is being rendered?

I'm currently developing a react movie application. I am facing an issue with the hero picture feature that displays a random popular movie or show. Whenever I click the button to open a modal, the useEffect function is triggered and changes the movie ...

What causes the data to flicker between the old and new values when the state is updated in ReactJS?

Currently, I am developing a single-page application that fetches data from the Star Wars API. In the character section of the project, the goal is to display characters per page with the ability to navigate to the next or previous pages by clicking on but ...

Problem with using puppeteer to interact with a dropdown menu

I have a project in which I am utilizing puppeteer to create a bot that can automatically check for my college homework assignments. The problem I am encountering is that when the bot tries to click on a dropdown menu, it fails and I receive an error messa ...

What is the best way to pass a conditional true or false value to React boolean props using TypeScript?

I am currently utilizing the Material UI library in combination with React and Typescript. Whenever I attempt to pass a conditional boolean as the "button" prop of the component, I encounter a typescript error stating: Type 'boolean' is not assi ...

What is the best way to transform an Object {} into an Array [] of objects with varying structures?

Within my javascript code, I am working with an object structure like this: let obj= { a: { a1: [5,5], a2: [6,6] }, b: { a1: [7,7], a2: [8,8] }, c: { a1: [9,9], a2: [3,3] } } The goal is to ...

Unable to locate the module model in sequelize

Having some trouble setting up a basic connection between Postgres and SQL using Sequelize. I keep getting an error where I can't require the model folder, even though in this tutorial he manages to require the model folder and add it to the sync, lik ...

Using Firebase Database, Angular2 employs UID (User ID) as the primary key

Creating a signup component in my app using Firebase as the authentication method and database. After registering a new user, a key is generated and all user information, including the UID from authentication, is saved in the database. I want to use the UI ...

What is the best way to incorporate animation into Bootstrap dropdowns?

Is there a way to incorporate animation into the dropdown feature? I'm assuming it can be achieved by adjusting popperConfig, but how exactly? Currently, the dropdown-menu has an automatically generated inline style, for example: position: absolute; ...

Having EventListeners set up across a single CSS class returns null when applied to different types of elements simultaneously

I want to create floating labels that resize dynamically when an input is clicked, similar to modern forms. I am using vanilla JS exclusively for this task. Currently, the setup works with the <input> tag. However, it does not work with the <text ...

Retrieving a JavaScript variable in PHP on the identical page by simply altering the div tag within the URL

I have a webpage called abc.php that showcases a table of image names. When a user clicks on an image name, an overlay page is loaded at #openModal on the same abc.php page. This new overlay page displays a list of sensor values related to the selected ima ...

Toggle the visibility of a div based on whether or not certain fields have been filled

Having a form with a repeater field... <table class="dokan-table"> <tfoot> <tr> <th colspan="3"> <?php $file = [ 'file' => ...

"Jest test.each is throwing errors due to improper data types

Currently, I am utilizing Jest#test.each to execute some unit tests. Below is the code snippet: const invalidTestCases = [ [null, TypeError], [undefined, TypeError], [false, TypeError], [true, TypeError], ]; describe('normalizeNames', ...

Exploring the capabilities of the hardware camera in Angular 2

Struggling to implement the tutorial in Angular2. The challenge lies in making navigator.mediaDevices.getUserMedia function properly. The error message indicates that mediaDevices is not recognized on type 'navigator'. Refer to the media capture ...

Data of an object disappears when it is passed to Meteor.call

In my React/Meteor project, I encountered an issue while trying to pass an object with data from the state to a method on the server for database insertion. Surprisingly, when the object is passed from the React component to the Meteor method, one of the c ...

Flexbox causing issues with relative positioning at the bottom of the screen in various browsers

My flex component looks like this: <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" ... width="100%" height="100%" creationComplete="init()"> ....... <components:Naviga ...

Erasing a comment creates empty spaces

I've encountered an issue with my idea whiteboard where removing comments leaves unwanted blank spaces between ideas. For example, if I have the following comments: But when I delete something: Is there a way to ensure that no gaps are left between ...

How Web Components interact with innerHTML within connectedCallBack

class Form extends HTMLElement { constructor() { super() } connectedCallback() { console.log(this) console.log(this.innerHTML) } } customElements.define("my-form", Form); I'm currently faci ...

arrange the elements in a specified sequence

I am trying to sort an array in a specific order var customOrder = { "1st Presentation / Meeting": 0, "Follow-On Meetings": 1, "Hold\/Uncategorized": 2, "MGL": 3, "PGL": 4, "BGL": 5, "RGL": 6, "SGL": 7, "Uncategorized Leads": 8, ...