【问题标题】:Typescript compiler not using _this with lambda functionsTypescript 编译器不使用 _this 和 lambda 函数
【发布时间】:2015-08-11 20:02:02
【问题描述】:

我有两个相同的指令(除了命名),编译器在另一个指令中创建了一个变量 _this 就好了,但在另一个指令中没有。它可能会有所不同,哪个好,哪个不好。 它们都有这样的链接功能:

link = (scope: IMyScope, element, attrs) => {
    scope.setVariable1 = () => {
        this.service.setVariable1(scope.variable1);
    }

还有一个问题是编译后的版本尝试使用 this.service(undefined) 而不是 _this.service。

【问题讨论】:

  • 您使用哪个版本的打字稿?
  • 您在编译后的文件中看到this.service 还是只是您的猜测?只有当目标是 ES6 时,TypeScript 才会在箭头函数中保留 this
  • TypeScript 1.4(昨天才更新到 1.5)。我看到服务的编译版本和 ES6 是目标。
  • 我通过使用控制器而不是链接函数解决了这个问题。这不是我想要的,但我花了太多时间试图让链接功能发挥作用。

标签: typescript


【解决方案1】:

不完全确定您的编译可能有什么问题,但通常我不会将指令声明为一个类而是一个函数。

    function yourDirective(yourService): ng.IDirective{
         return {
              //other directive properties
              link: (scope: IMyScope, element, atrrs) =>{
                     scope.setVariable1 = () => {
                         yourService.setVariable1(scope.variable);
                     }
              }
         };
     };
     yourDirective.$inject = ["yourService"];

     angular.module("app").directive("yourDirective", yourDirective);

那么你就不需要在链接函数中使用this了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-08
    • 2018-04-10
    • 2019-02-18
    • 1970-01-01
    • 2014-09-30
    相关资源
    最近更新 更多