I've encountered an issue while trying to call a controller function from a directive, specifically dealing with the "this" context problem. The logService becomes inaccessible when the function is triggered by the directive.
Below is the code for the controller:
class MainController implements IMainScope {
static $inject = ["LogService"];
constructor(private logService:ILogService) { }
sayHello(message:string) {
console.log("MainController sayHello", message);
// If called from directive, it throws 'Cannot read property 'logService' of undefined'
this.logService.log(message);
}
}
And here's the directive class:
class TestDirective implements ng.IDirective {
public restrict = "E";
public templateUrl = "test-directive.html";
public replace = true;
public scope:any = {
testFn: "&"
};
constructor() { }
public link:ng.IDirectiveLinkFn = (scope:TestDirectiveScope, element:ng.IAugmentedJQuery, attrs:ng.IAttributes):void => {
scope.hello = () => {
console.log("TestDirective", scope.firstName);
scope.testFn()(scope.firstName);
};
}
static factory():ng.IDirectiveFactory {
let directive:ng.IDirectiveFactory = () => new TestDirective();
return directive;
}
}
To illustrate the problem, you can check out this simple plunker example: http://embed.plnkr.co/Ov7crFZkkjDPzilX2BmL/