Skip to content

Instantly share code, notes, and snippets.

@xdissent
Last active December 18, 2015 00:39
Show Gist options
  • Save xdissent/5698004 to your computer and use it in GitHub Desktop.
Save xdissent/5698004 to your computer and use it in GitHub Desktop.
AngularJS Controllers with Class in Coffeescript http://plnkr.co/rEYMsS0rKo1ZC6O5LoxM
class AngularCtrl
# The namespace to use for module name generation
@ns: 'ns.controllers'
# Module name for the exported Angular module, or autogenerated if `null`
@module: null
# An array of module names required by the controller
@require: []
# Services to be injected into the controller constructor
@inject: []
# Determines the module name to export
@_module: ->
return @module if @module? and typeof @module is 'string'
dashed = @name.replace(/([A-Z][a-z0-9]+)(Ctrl)?/g, '-$1').toLowerCase()
"#{@ns}.#{dashed[1...dashed.length]}"
# Creates an Angular module containing the controller
@export: -> angular.module(@_module(), @require).controller @name, @inject.concat @
module.exports = AngularCtrl
require 'angular'
require './demo-ctrl' # Returns the `ns.controllers.demo` module
# Load the demo controller module
angular.module 'app', ['ns.controllers.demo']
<!doctype html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8">
<title>AngularJS Controllers with Class in Coffeescript</title>
</head>
<body>
<div ng-controller="DemoCtrl as demo">
<pre>$scope.prop => {{prop}}</pre>
<a ng-click="method()">$scope.method()</a><hr>
<pre>demo.prop => {{demo.prop}}</pre>
<a ng-click="demo.method()">demo.method()</a>
</div>
<script src="app.js"></script>
</body>
</html>
require './angular-ctrl'
class DemoCtrl extends AngularCtrl
# Explicitly name the module or default to 'ns.controllers.demo'
# @module: 'ns.controllers.overridden'
# Modules required by the controller
# @require: ['some.service', 'another.service']
# Services injected into the controller constructor
@inject: ['$scope', '$log']
constructor: ($scope, $log) ->
# Set up scope with a property and method
$scope.prop = 'foo'
$scope.method = -> $log.info 'scope method!'
# Set up controller with a property
@prop = 'bar'
@log = $log # Store log service for later
# Methods are available in views using the "Ctrl as foo" ng-controller syntax.
method: -> @log.info 'controller method!'
module.exports = DemoCtrl.export()
@wprater
Copy link

wprater commented Sep 17, 2013

Are you doing a similar abstraction (AngularCtrl) for Services etc?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment