Я пытаюсь вызвать функцию контроллера из директивы, и я столкнулся с проблемой «этого» контекста. logSerivce недоступен, если функция вызывается через директиву.Контроллер Angularjs как через typescript вызывает функцию контроллера из директивы
Здесь класс контроллера:
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
this.logService.log(message);
}
}
Вот класс директивы:
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;
}
}
Вот простой пример plunker который покрывает мою проблему: http://embed.plnkr.co/Ov7crFZkkjDPzilX2BmL/
Спасибо большое! Оно работает!! К сожалению, ваша демонстрационная ссылка не показывает версию обновления. Я изменил вызов: 'test-directive test- fn =" vm.sayHello (message) "' и вызов в директиве. 'scope.testFn ({message: scope.firstName});' [Вот новая демо-версия] (https://embed.plnkr.co/nd54cRZqMDtnVM4XXhog/). Еще раз спасибо! – stevo
@stevo Я полностью забыл обновить;) Спасибо –
Вы можете обновить свой первый код с помощью 'fn =" vm.sayHello (message) 'тоже. – stevo