Reputation: 5449
Hi I have been trying out typescript and so far everything looks good but I can not seem to figure out something.I am using angular so I will present my problem in the context of it.
This is my code:
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);
}
}
What I am trying to achieve is to be able to access the $http service when I click a button.The buttonClick function is binded on the view and I am omitting the html code because I do not think it is necesarry.
When I click the button I want to be able to make an ajax call to the server but the problem is that 'this' will refer to the context of the button in javascript not the context ofthe PersonCtrl so I can not access any of the variables I am declaring as private.
I am aware that the approach I am taking may not be the best way I jsut started learning typescript this morning so if there are any improvement that can be made please let me know
How can I access $scope and $http in the buttonClick function?
Upvotes: 3
Views: 750
Reputation: 106620
Change:
this.$scope.buttonClick = this.buttonClick;
To:
this.$scope.buttonClick = () => this.buttonClick();
This will generate the following JavaScript that preserves this
:
var _this = this;
this.$scope.buttonClick = function() { return _this.buttonClick(); };
Upvotes: 3
Reputation: 6250
this
in buttonClick is not what you expect it to be in the first place. It's not the controller but the method's own scope.
Therefore, you need to create a reference to this
- as I'm not that familiar with TypeScript (in CoffeeScript you could just use fat arrows), I'd go with the regular JavaScript approach:
private $scope: IPersonScope;
private $http: ng.IHttpService;
// declare var for reference of this
var _this;
init() : void {
// save the reference for use in other methods
_this = this;
// ...
}
buttonClick(): void {
console.log("-----------------ButtonClick------------------");
// use the reference to the controller's `this`
console.log(_this.$http);
}
Upvotes: 0