Search code examples
angularjstypescriptthisangularjs-serviceangularjs-watch

AngulaJS with typescript cannot access angular services in directive link function


I am pretty new in typescript and I am trying to create Angular.js directive written using typescript class and want to use external angular services in directive link function, invoked when $watch function received data. But no matter how I try, this keyword always link to the global window and I cannot access injected services. Help me please to do it. Here 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);
            });
}

Solution

  • Directive link function has controller/ctrl as third parameter and attributes/attrs as fourth parameter.

    Sample link function will look something like this:

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

    You can use controller reference to invoke the controller function and from there directly invoke the angular services function which you need for manipulation.

    Regards

    Ajay