The ability to reply to discussions is limited to PRO members. Want to join in the discussion? Click here to subscribe now.

Experimental "Controller as" Syntax

Experimental "Controller as" Syntax

5:20
The "controller as" syntax was added to AngularJS 1.2. This syntax abstracts the use of `$scope` in controllers, simplifying the syntax of your controllers.
Watch this lesson now
Avatar
egghead.io

The "controller as" syntax was added to AngularJS 1.2. This syntax abstracts the use of $scope in controllers, simplifying the syntax of your controllers.

Avatar
Alfonso

I faced the following problem today when trying to use controller as syntax. Using coffee script in a rails application, I had configured some routes using the route provider:

crmApp.app.config ['$routeProvider',($routeProvider) ->
    $routeProvider.when('/people',
        templateUrl: 'template.html'
        controller: 'crm.person.indexCtlr'
        controllerAs: 'ctlr2'}
    )
]

The controller was:

crmApp.controllers.controller('crm.person.indexCtlr', ['$scope','$location', ($scope, $location)->
    this.title = 'Title'
    this.data = [
        {firstName: 'firstname1', lastName: 'lastname1'}
        {firstName: 'firstname2', lastName: 'lastname2'}
    ]
])

And finally, my view:

<h1>{{ctlr2.title}}</h1>

The view was not displaying the title. To solve the problem i needed to add an extra return statement at the end of the controller:

crmApp.controllers.controller('crm.person.indexCtlr', ['$scope','$location', ($scope, $location)->
    this.title = 'Title'
    this.data = [
        {firstName: 'firstname1', lastName: 'lastname1'}
        {firstName: 'firstname2', lastName: 'lastname2'}
    ]
    return
])

to prevent coffee script from returning the result of the last statement.

Thanks to Joel for helping me resolve this issue.

In reply to egghead.io
Avatar
Nir

is this still considered experimental or is it safe to use now?

In reply to egghead.io
HEY, QUICK QUESTION!
Joel's Head
Why are we asking?