【发布时间】:2015-04-13 12:54:41
【问题描述】:
嗨,我一直在尝试打字稿,到目前为止一切看起来都不错,但我似乎无法弄清楚什么。我正在使用 angular,所以我将在它的上下文中提出我的问题。
这是我的代码:
class PersonCtrl{
private $scope: IPersonScope;
private $http: ng.IHttpService;
static $inject = ['$scope', '$http']
constructor($scope: IPersonScope, $http: ng.IHttpService) {
this.$scope = $scope;
this.$http = $http;
this.init();
}
init() : void {
this.$scope.fullName = 'Justin S.';
this.$scope.buttonClick = this.buttonClick;
console.log("-----------------Init------------------");
console.log(this);
}
buttonClick(): void {
console.log("-----------------ButtonClick------------------");
console.log(this.$http);
}
}
我想要实现的是当我单击一个按钮时能够访问 $http 服务。buttonClick 函数绑定在视图上,我省略了 html 代码,因为我认为没有必要。
当我单击按钮时,我希望能够对服务器进行 ajax 调用,但问题是“this”将引用 javascript 中按钮的上下文而不是 PersonCtrl 的上下文,因此我无法访问任何我声明为私有的变量。
我知道我所采用的方法可能不是我今天早上开始学习打字稿的最佳方式,所以如果有任何可以改进的地方,请告诉我
如何在buttonClick函数中访问$scope和$http?
【问题讨论】:
标签: angularjs typescript