stevo stevo - 20 days ago 11
TypeScript Question

Angularjs controller as via typescript invoke controller function from a directive

I'm trying to invoke a controller function from a directive and I run into the "this" context problem. The logSerivce is not accessible if the function gets called via directive.

Here the controller class:

class MainController implements IMainScope {

static $inject = ["LogService"];

constructor(private logService:ILogService) { }

sayHello(message:string) {
console.log("MainController sayHello", message);
// Cannot read property 'logService' of undefined if gets call from directive

Here 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);

static factory():ng.IDirectiveFactory {
let directive:ng.IDirectiveFactory = () => new TestDirective();
return directive;

Here is a simple plunker example which covers my problem:


The way you are calling testFn from directive isn't correct way. To pass data with calling function you have to first use


And while calling function from directive pass it in json/object format like {message: 'some value'} in parenthesis.

scope.testFn({message: scope.firstName});

Demo Plunkr