我已经注入了storageService但是我尝试使用this.storageService在链接函数中访问它给出了undefined。
任何人都可以帮我吗?
module App.Directive {
import Services = Core.Services;
import Shared = Core.Shared;
export class UserNav implements ng.IDirective {
restrict = 'A';
require: any = "^?ngModel";
scope = true;
templateUrl: any = "template/user-nav.html";
link: ng.IDirectiveLinkFn = function(scope, element, attributes, ngModel: any) {
var a = this.storageService.getItem("userInfo", false);
console.log("getting > " + a);
}
constructor(public routerService: Services.RouterService,
public storageService: Services.StorageService) {
}
static factory(): any {
var directive = (routerService: Services.RouterService,
storageService: Services.StorageService) => {
return new UserNav(routerService, storageService);
}
directive['$inject'] = ['routerService', 'storageService'];
return directive;
}
}
}
答案 0 :(得分:0)
所以问题在于链接功能
变化击>
module App.Directive {
import Services = Core.Services;
import Shared = Core.Shared;
export class UserNav implements ng.IDirective {
restrict = 'A';
require: any = "^?ngModel";
scope = true;
templateUrl: any = "template/user-nav.html";
link: ng.IDirectiveLinkFn = function(scope, element, attributes, ngModel: any) {
var a = this.storageService.getItem("userInfo", false);
console.log("getting > " + a);
}
constructor(public routerService: Services.RouterService,
public storageService: Services.StorageService) {
}
static factory(): any {
var directive = (routerService: Services.RouterService,
storageService: Services.StorageService) => {
return new UserNav(routerService, storageService);
}
directive['$inject'] = ['routerService', 'storageService'];
return directive;
}
}
}
要:
module App.Directive {
import Services = Core.Services;
import Shared = Core.Shared;
export class UserNav implements ng.IDirective {
restrict = 'A';
require: any = "^?ngModel";
scope = true;
templateUrl: any = "template/user-nav.html";
link(scope, element, attributes, ngModel: any) {
var a = this.storageService.getItem("userInfo", false);
console.log("getting > " + a);
}
constructor(public routerService: Services.RouterService,
public storageService: Services.StorageService) {
}
static factory(): any {
var directive = (routerService: Services.RouterService,
storageService: Services.StorageService) => {
return new UserNav(routerService, storageService);
}
directive['$inject'] = ['routerService', 'storageService'];
return directive;
}
}
}
击> <击> 撞击>
更新:以上答案不会奏效。因为链接函数用作回调,this
是全局对象。您必须将服务设置为模块中的变量,然后您才能通过范围访问它。 see my fiddle