AngularJS TypeScript指令链接功能

前端之家收集整理的这篇文章主要介绍了AngularJS TypeScript指令链接功能前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图使用TypeScript创建一个AngularJS指令.我的指令需要“ngModel”,我也使用我的指令中注入的自定义服务.
我的主要问题是我的服务无法在我的链接功能中使用.

以下是我要实现的一个例子:

module app.directives {

    export var directiveName: string = "theDirective";

    angular.module("myApp").directive(directiveName,(myFactory: app.services.MyFactory) =>
           {
                return new MyDirective(myFactory);
           });

    export interface IMyDirectiveScope extends ng.IScope {
        ngModel: ng.INgModelController;
    }

    export class MyDirective implements ng.IDirective {

        restrict = "A";
        require = "ngModel";
        scope = {
            ngModel:'='
        }

        constructor(private myFactory: app.services.MyFactory) {

        }


        link(scope: IMyDirectiveScope,elem: JQuery,attributes: ng.IAttributes,ngModel: ng.INgModelController) {
            //this is window here

            elem.bind('blur',(evt: JQueryEventObject) => {  
                 //keyword this is also window here,so yeah bummer indeed
                 validate(); 
            });

            function validate() {
                 //I need to use my factory here,but I can seem to get it.
                 //this is always window and I'm kinda stuck here
            }
        }
    }
}

我似乎找不到一些更高级的东西在这个话题.所有的示例我都没有发现似乎不使用服务或复杂的链接功能.
请以某种方式回答这个问题.这是你想的诡计.

更新:我的链接函数内的“this”是窗口而不是“MyDirective”对我来说没有什么意义.任何想法为什么会这样?

类对于控制器和指令控制器来说非常有用,但是我不认为我会为整个指令使用一个.但是如果你想要你可能要这样做:
export class MyDirective implements ng.IDirective {

    public link;

    restrict = "A";
    require = "ngModel";
    scope = {
        ngModel:'='
    }

    constructor(private myFactory: app.services.MyFactory) {
        this.link = this.unboundLink.bind(this);
    }


    unboundLink(scope: IMyDirectiveScope,ngModel: ng.INgModelController) {
        //Now you should be able to access myFactory
        this.myFactory.doSomething();

        elem.bind('blur',(evt: JQueryEventObject) => {  
             //keyword this is also window here,so yeah bummer indeed
             validate(); 
        });

        function validate() {
             //I need to use my factory here,but I can seem to get it.
             //this is always window and I'm kinda stuck here
        }
    }
}

编辑:没有类,你可以这样做:

angular.module("myApp").directive("theDirective",function(myFactory: app.services.MyFactory) {
        return {
            restrict: 'A',require: 'ngModel',scope: {'ngModel': '='},link: function(scope: IMyDirectiveScope,ngModel: ng.INgModelController) {
                //You can access myFactory like this.
                myFactory.doSomething();
            }
        }
    }
);
原文链接:https://www.f2er.com/angularjs/142707.html

猜你在找的Angularjs相关文章