【发布时间】:2015-06-25 15:25:27
【问题描述】:
我通过设置回调函数从 Angularjs 注册“$routeChangeSuccessEvent”。引发事件时,我无法通过“this”访问我的控制器实例。当前这个实例是未定义的。
我的完整 TypeScript 代码:
export class Ctlr {
static $inject = ["$rootScope","$route"];
constructor(private $scope: ng.IRootScopeService) {
this.Scope = $scope;
this.Title = "";
//this.Scope.$on("$routeChangeSuccessEvent", this.onRouteChangeStart);
this.RegisterEvents();
}
private RegisterEvents(): void {
this.Scope.$on("$routeChangeSuccessEvent",(event: ng.IAngularEvent, args: any) => {
//this is undefined
console.log(this);
});
}
public Scope: ng.IScope;
public Title: string;
public onRouteChangeStart(event: ng.IAngularEvent, args: any) {
//this is undefined
this.Title = args.$$route.name);
}
}
}
我可以通过以下方式访问 Title 属性:
private RegisterEvents(): void {
var ref = this.Title;
this.Scope.$on("$routeChangeSuccessEvent",(event: ng.IAngularEvent, args: any) => {
ref = args.$$route.name;
});
}
但这不是一个真正的解决方案,因为 angularJS 不会更新它的视图。看来我没有找到正确的参考。如果那不可能,那么整个 angularjs 事件似乎都不是 useabel - 那不可能吗?
我也没有找到任何关于这种奇怪行为的话题。这个问题有解决办法吗?
【问题讨论】:
-
小提示:
constructor(private $scope: ...)表示$scope被放置在对象属性中,因此this.Scope = $scope;是多余的。只需使用this.$scope。
标签: javascript angularjs typescript