Justin Boyson Justin Boyson - 1 year ago 110
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>


.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) {

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 Source

So my scope is messed up somehow

Use an arrow function instead of a method.


class MyController {
  constructor() {}

  saveFn = (value) => {



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download