Typescript with AngulaJS is unable to access Angular services within a directive's link function

I'm new to TypeScript and I'm attempting to create an Angular.js directive using a TypeScript class. I want to utilize external Angular services in the directive's link function, which is called when the $watch function receives data. However, no matter what I do, the 'this' keyword always points to the global window object, making it impossible for me to access the injected services. Can someone please help me solve this issue? Below is my directive:

module Portal.MainMenu {
    class MenuScrollDirective implements ng.IDirective {
        static $inject = ["$timeout", "$window"];

        constructor(private $timeout: ng.ITimeoutService, private $window: ng.IWindowService) { } 
        restrict = "EA";
        scope = {
            expanded: "=",
            tplChanged: "=",
            fullView: "="
        };
        link = ($scope: ng.IScope, el: IJQSlimScroll) => {
            var settings = {
                position: 'left',
                size: '5px'
            };

         init();

         function init() {
             $scope.$watch('expanded',(cur, prev) => {
                 cur && adjustScroll();
             });
          }

         function adjustScroll() {
             var winH = this.$window.innerHeight //this - refers to Window here 
                                               //but I need to access service

             this.$timeout(() => {
                  //need access to el here
              }); //same here 'this' is global 
          }
      }

      angular.module('portal.mainMenu')
           .directive('menuScroll', ($timeout: ng.ITimeoutService, $window: ng.IWindowService) => {
                return new MenuScrollDirective($timeout, $window);
            });
}

Answer №1

When working with directive link functions, remember that the controller/ctrl is the third parameter and attributes/attrs is the fourth parameter.

An example of a link function could be:

link = ($scope: angular.IScope, el: angular.IAugmentedJQuery, ctrl: Function, attrs: angular.IAttributes).

You have the ability to use the controller reference to call the controller function and then access any necessary Angular services for manipulation.

Best regards,

Ajay

Answer №2

Working with TypeScript and angular simultaneously is a new experience for me, but the code provided does not seem to follow typical TypeScript conventions. A more idiomatic approach would be something like this:

class MenuScrollDirective implements ng.IDirective {
    static $inject = ["$timeout", "$window"];

    constructor(private $timeout: ng.ITimeoutService, private $window: ng.IWindowService) { 
        this.restrict = "EA";
        this.scope = {
            expanded: "=",
            tplChanged: "=",
            fullView: "="
        };
    } 

    link($scope: ng.IScope, el: IJQSlimScroll) {
        $scope.$watch('expanded', (cur, prev) => {
            cur && this.adjustScroll();
        });
    }

    private adjustScroll() {
        var winH = this.$window.innerHeight;
        this.$timeout(() => {}); 
    }
}

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

Discover how to transform the ist date and time format to est with the power of angularjs

I need to transform the date from 5/3/2018 to Mon Mar 5 01:54:07 EST 2018 format using angularjs before sending it to the backend. ...

The [image link] in the NextJS image was loaded in advance using link preload, but it was not utilized within a short time after the window finished loading

While working on my blog website with NextJS, I encountered a warning in the console related to using next/image: The resource http://localhost:3000/_next/image... was preloaded using link preload but not used within a few seconds from the window's lo ...

An effective method for creating responsive layouts for custom-shaped HTML elements in a board game

Can anyone guide me on aligning spaces responsively on a board in HTML using Angular 1.x? I've tried using vw/vh's and %s, but consistency breaks on different view sizes. Any straightforward suggestions to address this issue? Avoiding multiple c ...

What is the best way to retrieve HTML content using an Angular method?

Okay, so the title might not be the greatest...but I couldn't think of anything better: I want to emphasize search keywords in the result list...that's why I'm having trouble with this problem. CSS: .highlightText{ font-weight: bold; } In ...

Enhancements to managing universal configuration object across the entire application

My current project involves working on an application with multiple products. To streamline product-specific configuration and eliminate the need for excessive if-else statements, I am looking to implement product-specific config keys that are consistently ...

What is the best way to trim a string property of an object within an array?

I am seeking a solution to access the "description" property of objects within an array and utilize a string cutting method, such as slice, in order to return an array of modified objects. I have attempted using for loops but have been unsuccessful. Here ...

Issue with adding to lightbox feature when loading content dynamically using AJAX PHP is not functioning as expected

Hey there! I've encountered an interesting issue with my code that adds models to a lightbox. It's functioning perfectly on static pages like this one. $scope.add = function(permalink, post_id) { if (typeof(Storage) !== "undefined") { ...

AOT compile error due to Angular interpolation syntax

I am facing an issue while compiling my application. The AOT compiler is showing an error related to Angular interpolation in an Angular 2 form: Property 'address' does not exist on type 'FirebaseObjectObservable'. Here's a sn ...

The token 'x.id' came out of nowhere - instead, [x.id}})] should have been expected in column 11 of the expression [elimina({{x.id}})]

Encountering an error: Error: [$parse:syntax] Syntax Error: Token 'x.id' is unexpected, expecting [:] at column 11 of the expression [elimina({{x.id}})] starting at [x.id}})]. This is the code snippet causing the issue: <tr ng-repeat="x i ...

What is the process for upgrading TypeScript to the newest version using npm?

My current TypeScript version on my machine is 1.0.3.0 and I am looking to upgrade it to the latest version, which is 2.0. Could someone please guide me on how to accomplish this using npm? ...

The Tauri JS API dialog and notification components are failing to function, resulting in a null return value

Currently, I am getting acquainted with the tauri framework by working on a small desktop application. While testing various tauri JS API modules, most of them have been functioning as expected except for the dialog and notification modules. Whenever I tes ...

Angular dependency issue: Expected '{' or ';' for @types/node

I encountered an error while running "ng serve" in my Angular application. Originally built as Angular 2, it was upgraded to Angular 8 (with attempts at versions 6 and 7 along the way). However, after migrating from Angular 5, I started experiencing errors ...

Angular is having trouble showing an image sourced from OMDBAPI

Currently, I am delving into the world of AngularJS. For my project, I aim to showcase movie posters sourced from http://www.omdbapi.com. HTML <div ng-app="moviesBrowserApp"> <div ng-controller="moviesCtrl"> <strong> ...

Angular Partial Submit/Procession

I have more experience with JSF than Angular or jQuery. I am interested in learning about partial submit and processing in web development. Is there an easy way to achieve this? Specifically, I would like to understand how to implement partial page process ...

Encountering "net::ERR_EMPTY_RESPONSE" error when making a HTTP PUT request using the HUE API in JavaScript

GET requests are functioning properly. PUT requests made from the API Debug tool are also working correctly. However, both PUT and POST requests, regardless of the data or API URL used, are resulting in the following error: example: OPTIONS net::ERR_ ...

Choose a value, then multiply it by a number using a reactive

I have been attempting to multiply a fixed value by the selected value of a mat-select element, for example A x B, where A remains constant and does not change while B is the changing value from the mat-select. After performing this multiplication, I aim ...

What is the process of reading an excel file in angularjs?

I attempted to read an Excel file by following a tutorial I found at . Unfortunately, I encountered an undefined situation in the highlighted line below while trying to do so in IE11. var reader = new FileReader(); reader.onload = function( ...

Type of Data for Material UI's Selection Component

In my code, I am utilizing Material UI's Select component, which functions as a drop-down menu. Here is an example of how I am using it: const [criteria, setCriteria] = useState(''); ... let ShowUsers = () => { console.log('Wor ...

Struggling to make type definitions work in react-hook-form 7

Upon defining the types of my form fields, I encountered an issue where each field seems to take on all three different types. This is puzzling as I have specified 3 distinct types for my 3 different fields. What could be causing this confusion? https://i ...

Exploring Angular2's interaction with HTML5 local storage

Currently, I am following a tutorial on authentication in Angular2 which can be found at the following link: https://medium.com/@blacksonic86/authentication-in-angular-2-958052c64492 I have encountered an issue with the code snippet below: import localSt ...