Skip to content

Instantly share code, notes, and snippets.

@kosz
Created November 4, 2014 21:17
Show Gist options
  • Save kosz/c9c56f9e53e63a8fd10a to your computer and use it in GitHub Desktop.
Save kosz/c9c56f9e53e63a8fd10a to your computer and use it in GitHub Desktop.
# This class facilitates writting Angular Controllers as OOP style classes rather than
# declaring an expensive method everytime the constructor is ran
# It MUST be extended by any Controller written as a class.
# That class MUST implement a constructor and call it's super
# NOTE: I have second doubts about this because
# 1) it doesn't do things the angular way,
# 2) it's coffeescript specific more or less
# 3) it requires specific code to be written in the implementing classes
# 4) if minification is not configured to not mangle variable name, this code will fail
# In a Rails+CoffeeScript environment with minification setup as required, this works perfectly however
# Especially serving people more used to Java/Ruby oop and less used to JS oop
class AngularController
private_methods: ['inherit_scope']
constructor: ->
@inherit_scope()
inherit_scope: =>
@scope[key] = value for key, value of @ when key not in @private_methods
window.AngularController = AngularController
# Usage
#class BaseCtrl extends AngularController
# constructor: ($scope) ->
# @scope = $scope
# super
# method_that_will_be_attached_to_the_angular_scope: () =>
# # ...
# <!-- Then in HTML -->
# <div ng-controller="BaseCtrl">
# <button ng-click="method_that_will_be_attached_to_the_angular_scope()"></button>
# </div>
# <!-- will call the method declared on the class. This can then be used by another controller as such : -->
# <div ng-controller="ChildCtrl">
# <button ng-click="method_that_will_be_attached_to_the_angular_scope()"></button>
# </div>
#
# Where :
#class ChildCtrl extends BaseCtrl
# constructor: ($scope) ->
# @scope = $scope
# super
# # does not implement the method, but the angular ng-click above will work, because the method is extended from the
# # extended class 'BaseCtrl'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment