打字稿 AngularJs $scope.vm 模式

Typescript AngularJs $scope.vm pattern

我将 Typescript 与 AngularJs 一起使用,并使用您的模式:

$scope.vm = this;

然后只需在 class 上添加您的属性和方法。然而我突然想到,当我需要访问一个服务时,我在我的 class 上将其设为 属性,然后将其添加到我的范围,这使得我的范围可能非常大。我的理解是我们希望保持控制器范围小。由于 angular 使用脏检查,这是否意味着任何时候我拥有整个范围(控制器 class)的任何服务的任何更改都将被重新处理?

所以我的问题是,我是不是偏离了基地,这没什么大不了的?

如果这是一个问题,其他人是如何解决的?

谢谢

understanding is we want to keep the controller scope small. Since angular uses dirty checking doesn't this mean that any time anything changes on any services I have the whole scope (controller class) will be reprocessed?

没有。 Angular 仅区别您绑定或观看的内容。没有人在看服务上的东西。

尝试将您的控制器声明为 class 并使用 thiscontrollerAs

$scope.vm 模式之所以有用,只是因为 this 可能绑定到 Javascript 中的不同事物,尤其是当 "class" 完全在构造函数中声明时。当您使用 controllerAs 变量调用 Typescript class 的方法时,这通常不是问题,因为 this 的定义非常明确。

编辑:

Style Y031 and Y032 来自 angular 风格指南解释了为什么 vm 是必要的,即 this 混淆。

在 TypeScript 中不需要它,因为 this 的语义非常清晰,在需要传递函数引用的情况下,可以使用 lambdas ((...) => ...) 来捕获 this.