Angular 关于控制器的文档

Angular documentation about controller this

我最近在 angular 文档 (https://code.angularjs.org/1.4.9/docs/guide/providers) 中读到:

myApp.controller('DemoController', ['clientId', function DemoController(clientId) {
  this.clientId = clientId;
}]);

关联到:

<html ng-app="myApp">
  <body ng-controller="DemoController as demo">
    Client ID: {{demo.clientId}}
  </body>
</html>

然后我很惊讶,因为使用 this 而不是注入的 $scope 服务。

我尝试重现成功,然后我想知道是否有人可以解释一个使用控制器实例比注入更可取的用例 $scope?

为什么最好使用 controller asthis guide 中有详细描述。

Why?: Controllers are constructed, "newed" up, and provide a single new instance, and the controllerAs syntax is closer to that of a JavaScript constructor than the classic $scope syntax.

Why?: It promotes the use of binding to a "dotted" object in the View (e.g. customer.name instead of name), which is more contextual, easier to read, and avoids any reference issues that may occur without "dotting".

Why?: Helps avoid using $parent calls in Views with nested controllers.

但是最好使用专门的变量来访问控制器实例:

myApp.controller('DemoController', ['clientId', '$scope', function DemoController(clientId, $scope) {
  var self = this;
  self.clientId = clientId;

  //to watch the vars
  $scope.$watch('self.clientId', function(new, old) {});
}]);

John Papa's style guide about controllerAs:

... the controllerAs syntax is closer to that of a JavaScript constructor than the classic $scope syntax

It promotes the use of binding to a "dotted" object in the View (e.g. customer.name instead of name), which is more contextual, easier to read, and avoids any reference issues that may occur without "dotting".

Helps avoid using $parent calls in Views with nested controllers.

我在日常使用中发现的最大好处是它在控制器中提供了命名空间的概念,而不仅仅是让“自由变量”在你的标记周围漫游.

如果您有嵌套控制器,这一点尤其重要,因为它提供了命名空间变量(即使是同名变量)的方法,但要确保它们位于正确控制器的上下文中。