【问题标题】:Typescript/AngularJS: $scope undefined outside of constructorTypescript/AngularJS:在构造函数之外未定义 $scope
【发布时间】:2016-09-28 09:25:14
【问题描述】:

为什么我在构造函数之外没有$scope 的范围,除非我使用粗箭头定义我的函数?或者是否可以在不使用粗箭头定义函数的情况下访问 $scope?

namespace FooBar {
    export interface MyScope extends ng.IScope {
        message: string;
    }

    export class SandboxCtrl {
        static $inject = ["$scope", "$timeout"];
        private scope: MyScope;
        private timeout: ITimeoutService;
        constructor($scope: MyScope, $timeout: ng.ITimeoutService) {
            this.scope = $scope;
            this.timeout = $timeout;
            timeout(this.foo, 1000); // does not work
            timeout(this.bar, 1000); // works
        }

        public foo() {
            this.scope.message = "foo bar"; // does not work
        }

        bar = () => {
            this.scope.message = "foo bar"; // works
        }
    }
}

更新我注意到我没有分享整个问题,因为我不知道这是因为$timeout 指令导致了问题。无论如何,我更新了我的示例。

【问题讨论】:

  • 你有没有在你的项目中添加了 DefinedTyped angualer 文件?
  • @NinjaDeveloper 是的,我有。

标签: angularjs typescript angularjs-scope


【解决方案1】:

尝试将$scope 定义为控制器类中的属性:

    export class SandboxCtrl {
        static $inject = ["$scope"];
        constructor(private $scope: MyScope) {

        }
    }

【讨论】:

  • 你是对的。我经常使用它,我声明的函数是常规的,不需要胖语法。据我所知,打字稿处理 this 内部函数 - 确保范围是控制器的。
【解决方案2】:

无需过多详细说明,通过使用bindthis 绑定到函数即可解决问题。

timeout(this.foo.bind(this), 1000);

【讨论】:

    【解决方案3】:

    超时(this.foo, 1000); // 不工作

    这是因为foo 是一个未绑定的函数,this 的值将由调用者驱动。

    只需使用箭头函数?

    更多

    这里有介绍https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

    【讨论】:

      猜你喜欢
      • 2018-09-28
      • 2015-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多