Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
AngularJS + Coffeescript Constructor Class with Inheritance
app = angular.module 'myapp', []
# simple class exemple - minification safe
class MySimpleCtrl
@$inject: ['$scope']
constructor: (@scope) ->
# attach viewmodel data to the scope:
@scope.demo = 'Simple class demo'
# expose controller functions to scope
angular.extend @scope,
clear: @clear
# use => to bind function to controller instance
clear: =>
@scope.demo = ""
app.controller 'MySimpleCtrl', MySimpleCtrl
# inheritance exemple - just proof of concept
class Controller
@register: (app) -> app.controller @name, @ # not sure it's cross browser, not minification safe
@inject: (args...) -> @$inject = args
constructor: (args...) ->
for key, index in @constructor.$inject
@[key] = args[index]
class MyCtrl extends Controller
@register app
@inject '$scope'
constructor: ->
@$scope.demo = "Inheritance exemple"
@$scope.clearText = @clearText
clearText: =>
@$scope.demo = ""
angular.bootstrap document, ['myapp']
<div ng-controller="MySimpleCtrl">
<input type="text" ng-model="demo">
<h1 ng-click="clearText()">{{ demo }}</h1>
<div ng-controller="MyCtrl">
<input type="text" ng-model="demo">
<h1 ng-click="clearText()">{{ demo }}</h1>
<script src=""></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment