AngularJS TypeScript指令链接功能
发布时间:2020-12-17 07:39:42 所属栏目:安全 来源:网络整理
导读:我试图使用TypeScript创建一个AngularJS指令.我的指令需要“ngModel”,我也使用我的指令中注入的自定义服务. 我的主要问题是我的服务无法在我的链接功能中使用. 以下是我要实现的一个例子: module app.directives { export var directiveName: string = "th
我试图使用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(); } } } ); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |