Justin Boyson Justin Boyson - 4 months ago 6
TypeScript Question

Invoking function breaks scope

Same issue as here: AngularJS directive binding a function with multiple arguments

Following this answer: http://stackoverflow.com/a/26244600/2892106

In as small of a nutshell as I can.

This works:

<my-directive on-save="ctrl.saveFn"></my-directive>


With:

angular.module('app')
.controller('MyController', function($scope) {
var vm = this;
vm.saveFn = function(value) { vm.doSomethingWithValue(value); }
});


But when I convert to Typescript and use real classes, this breaks.

class MyController {
constructor() {}

saveFn(value) {
this.doSomethingWithValue(value);
}
}


In the Typescript version when debugging, "this" is referencing the Window global. So my scope is messed up somehow, but I don't know how to fix it. How can I get "this" to refer to MyController as expected?

Answer

So my scope is messed up somehow

Use an arrow function instead of a method.

Fixed

class MyController {
  constructor() {}

  saveFn = (value) => {
    this.doSomethingWithValue(value);
  }
}

More

https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html