Skip to content

Instantly share code, notes, and snippets.

@0xBADC0FFEE
Created April 19, 2014 14:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0xBADC0FFEE/11086467 to your computer and use it in GitHub Desktop.
Save 0xBADC0FFEE/11086467 to your computer and use it in GitHub Desktop.
AngularJS + Coffeescript Constructor Class with Inheritance http://jsfiddle.net/g/bXFdM/5/
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: ->
super
@$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>
<div ng-controller="MyCtrl">
<input type="text" ng-model="demo">
<h1 ng-click="clearText()">{{ demo }}</h1>
</div>
<script src="http://code.angularjs.org/1.0.1/angular-1.0.1.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment