Angular Directives with Coffeescript Class Controllers

The first time you try to set up a directive using a Coffeescript class, you might end up with something like this:

class MyControllerName
    @$inject: ['my', 'services', 'here']
    constructor: (@my, @services, @here) ->
        # constructor code

angular.module('mymodule').controller 'MyControllerName', MyControllerName

angular.module('mymodule').directive 'myDirective', ->
    return {
        restrict: 'AE'
        scope:
            variable: '='
        controller: 'MyControllerName'
    }

When you try it, you'll notice that your controller seems to not be hooked up to the directive even though you're obviously connecting them properly.

Interestingly enough, directives do not call new on their controllers by default, and Coffeescript class controllers must be instantiated with the new keyword. To get Angular to call new on a controller attached to a directive, you need to use the controllerAs option like this:

angular.module('mymodule').directive 'myDirective', ->
    return {
        restrict: 'AE'
        scope:
            variable: '='
        controller: 'MyControllerName'
        controllerAs: 'myControllerName'
    }

Hopefully this is helpful, as it encourages the use of controllerAs syntax and class based controllers which lead to cleaner code!