ng-Controller 语法——什么是别名?

ng-Controller syntax -- what is the alias for?

我不明白如何使用 controllerAS 语法。在我的演示应用程序中,我有一个具有以下语法的视图控制器:

ng-controller="mainController as ctrl"

在那个HTML的范围内,我有这个代码:

<h2>{{ ctrl.person.name }} <small>{{ ctrl.person.jobTitle }}</small></h2>
  <p class="lead"><a href="mailto:{{ ctrl.person.email }}">{{ ctrl.person.email }}</a></p>

尽管将控制器别名设置为 'ctrl',但我的表达式不会打印出来。仅当我从 'mainController' 控制器中删除 'ctrl' 别名时,表达式才会打印出来。

我想我不明白作用域是如何工作的。这是我在结束正文标记处的 js 脚本:

<script type="text/javascript">
var directory = angular.module('directory', []);
directory.controller('mainController', ['$scope','$http',
  function($scope, $http) {
    $http.get('roster.json').success(function(data) {
      $scope.people = data;
      $scope.peopleOrder = 'name';
    });
  }
]);</script>

我的plunker link is here。有人可以帮我看看原因吗?谢谢

This article 将为您指明解决问题的正确方向。

要点是,使用 controllerAs 语法后,您不再使用 $scope,而是使用 this

首先,您的路由器必须知道:

.state('main', {
    url: '/',
    templateUrl: '...',
    controller: 'mainController',
    controllerAs: 'ctrl'
})

然后,数据绑定发生在 this 而不是 $scope,所以这个片段:

$scope.people = data;
$scope.peopleOrder = 'name';

...变成:

this.people = data;
this.peopleOrder = 'name';

那么,在您看来,您可以访问数据:

<pre>{{ people }}</pre>

我假设 people 是一个数组,因此您将不得不使用 ngRepeat.

进行迭代