在 ng-controller 中有 "as ctrl" 与没有它

Having "as ctrl" in ng-controller versus not having it

我对 angular 材料还很陌生。我正在尝试使用自动完成功能。

我这里有一些自动完成示例代码; http://codepen.io/helpme/pen/KzxXPQ

首先让我难过的是这个控制器的声明;

<div ng-controller="DemoCtrl as ctrl" layout="column" ng-cloak="" ng-app="MyApp">

在我过去的 angularjs 代码中,ng-controller 是这样声明的 <div ng-controller="DemoCtrl" 而没有 as ctrl

as ctrl和没有有什么区别?如果删除 as ctrlhttp://codepen.io/helpme/pen/KzxXPQ 处的代码应该如何更改?

John Papa 的优秀 Angular style guide(所有新 Angular 开发者 IMO 的必备读物)很好地涵盖了这一点:

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.

第 2 点和第 3 点对我来说是关键 - 它使您的代码更易于阅读和维护。