【问题标题】:Angularjs controller as via typescript invoke controller function from a directiveAngularjs控制器通过打字稿从指令调用控制器功能
【发布时间】:2017-02-15 16:35:16
【问题描述】:

我正在尝试从指令中调用控制器函数,但遇到了“this”上下文问题。如果函数通过指令调用,则 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/

【问题讨论】:

    标签: angularjs typescript angularjs-directive


    【解决方案1】:

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

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

    从指令调用函数时,将其以 json/object 格式传递,如括号中的{message: 'some value'}

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

    Demo Plunkr

    【讨论】:

    • 非常感谢!有用!!不幸的是,您的演示链接没有显示更新版本。我更改了调用:test-directive test- fn="vm.sayHello(message)" 和指令中的调用。 scope.testFn({message: scope.firstName});Here is the new demo version。再次感谢!
    • 您可能也想用fn="vm.sayHello(message) 更新您的第一个代码。
    • @stevo 真的很糟糕,我昨天午夜感到困倦,感谢您指出,谢谢:)
    【解决方案2】:

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

        sayHello = (message:string)  => { ... }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多