0

我是打字稿的新手,我正在尝试创建使用打字稿类编写的Angular.js指令,并希望在指令链接函数中使用外部角度服务,在$watch函数接收数据时调用。但是无论我怎么尝试,这个关键字总是链接到全局窗口,我无法访问注入的服务。请帮我做。这是我的指令:

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

2 回答 2

0

我不习惯 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(() => {}); 
    }
}
于 2016-04-04T19:12:23.570 回答
0

指令链接函数的第三个参数是 controller/ctrl,第四个参数是 attributes/attrs。

示例链接函数将如下所示:

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

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

问候

阿杰

于 2016-04-05T11:25:41.653 回答