redshift
redshift

Reputation: 5227

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

I don't understand how to use the controllerAS syntax. In my demo app, I have a view controller with the following syntax:

ng-controller="mainController as ctrl"

Within the scope of that HTML, I have this code:

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

My expressions won't print despite having the controller alias set as 'ctrl'. The expressions will only print if I remove the 'ctrl' alias from the 'mainController' controller.

I think I am not understanding how scope works. Here's my js script at the closing body tag:

<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>

My plunker link is here. Can someone help show me the reasoning? Thanks

Upvotes: 0

Views: 474

Answers (1)

Pier-Luc Gendreau
Pier-Luc Gendreau

Reputation: 13814

This article will point you in the right direction for solving your problem.

The gist of it is that with the controllerAs syntax, you no longer use $scope, but this instead.

First off, your router has to be made aware:

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

Then, databinding happens on this rather than $scope, so this snippet:

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

...becomes:

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

Then, in your view, you can access the data:

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

I assume people is an array so you will have to iterate using ngRepeat.

Upvotes: 4

Related Questions