带有打字稿的 AngularJS 无法访问指令 link 函数中的 angular 服务

AngulaJS with typescript cannot access angular services in directive link function

我是 typescript 的新手,我正在尝试创建使用 typescript [=29= 编写的 Angular.js 指令] 并希望在指令 link 函数中使用外部 angular services,在 $watch 时调用函数接收数据。但无论我如何尝试,this 关键字总是 link 到全局 window,我无法访问注入的服务。请帮我做。 这是我的指令:

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

我不习惯将 TypeScript 和 angular 一起使用,但这对我来说看起来不像是惯用的 TypeScript。你可能想要这样的东西:

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(() => {}); 
    }
}

指令 link 函数具有 controller/ctrl 作为第三个参数和 attributes/attrs 作为第四个参数。

示例 link 函数将如下所示:

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

您可以使用控制器引用来调用控制器函数,并从那里直接调用您需要进行操作的 angular 服务函数。

此致

阿杰