Loukas Avramidis
Loukas Avramidis

Reputation: 537

Using an AngularJS controller's scope in Typescript

The situation: I recently started using Typescript and am currently integrating it into my AngularJS web application. I have been using the 'controller as' syntax instead of $scope where possible.

The issue: I can't seem to find a proper way to replace var self = this; I started replacing vm with this everywhere which soon got me to a dead-end when inside of forEach functions, click events etc.

My temporary solution: casting var self = this; in each function, since I can't cast it globally as far as I understand. It also doesn't work in all cases.

My question: have I missed something obvious? Is there a better way to access the controller's scope?

Upvotes: 2

Views: 736

Answers (1)

Brocco
Brocco

Reputation: 64883

Fat Arrow functions to the rescue!!!

There is really no need to use var self = this in TypeScript...

Fat arrow functions preserve the (lexical) scope (meaning of this) inside of callback functions:

var self = this;
fooService.doSomething()
  .then(result => {
    console.assert(this === self);  // this is valid and true
  });

For your specific example:

items.forEach((item) => {
  this.somethingElse = item; // (no need for self)
});

Note This is not really a feature of TypeScript, but more so a function of ES6/ES2015

Further Explanation

Upvotes: 5

Related Questions