Angularjs控制器作为via typescript从指令

时间:2016-10-06 19:37:46

标签: angularjs typescript angularjs-directive

我试图从指令中调用一个控制器函数,然后我遇到了"这个"背景问题。如果通过指令调用该函数,则无法访问 logSerivce

这里是控制器类:

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/

2 个答案:

答案 0 :(得分:0)

您从指令调用testFn的方式不正确。要使用调用函数传递数据,您必须先使用

ng-click="vm.sayHello(message)"

虽然从指令调用函数,但在json / object格式中将它传递给括号中的{message: 'some value'}

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

Demo Plunkr

答案 1 :(得分:0)

应该作为回调传递的方法(Angular绑定属于此类别)应该绑定到它们的上下文。对于TypeScript,最好的方法是将方法定义为箭头函数:

    sayHello = (message:string)  => { ... }
相关问题