Skip to content

Instantly share code, notes, and snippets.

@odiak
Last active August 29, 2015 14:03
Show Gist options
  • Save odiak/5df72e172ee312e96b0a to your computer and use it in GitHub Desktop.
Save odiak/5df72e172ee312e96b0a to your computer and use it in GitHub Desktop.
Extending controller on Angular Classy
angular.module('classyExtends', ['classy-core']).classy.plugin.controller
name: 'classyExtends'
classObjs: {}
waitingClassConstructors: {}
options:
enabled: true
convertInject: (classObj) ->
if angular.isArray classObj.inject
_inject = {}
for i in classObj.inject
_inject[i] = '.'
classObj.inject = _inject
extend: (classConstructor, classObj, baseClassObj) ->
for prop of baseClassObj
if typeof classObj[prop] == 'undefined'
classObj[prop] = classConstructor::[prop] = baseClassObj[prop]
@convertInject classObj
@convertInject baseClassObj
isInitialized = classConstructor.__classDepNames?
if isInitialized and not classConstructor.__classyControllerInjectObject?
classConstructor.__classyControllerInjectObject = {}
for dep in classConstructor.__classDepNames
classConstructor.__classyControllerInjectObject[dep] = '.'
for key, val of baseClassObj.inject
classObj.inject[key] = val
if isInitialized
if key not in classConstructor.$inject
classConstructor.$inject.push key
classConstructor.__classDepNames.push key
classConstructor.__classyControllerInjectObject[key] = val
preInitBefore: (classConstructor, classObj, module) ->
if classObj.extends
baseClassObj = @classObjs[classObj.extends]
if baseClassObj
@extend classConstructor, classObj, baseClassObj
else
@waitingClassConstructors[classObj.name] = classConstructor
@classObjs[classObj.name] = classObj
for className, waitingClassConstructor of @waitingClassConstructors
waitingClassObj = @classObjs[className]
if waitingClassObj.extends == classObj.name
@extend waitingClassConstructor, waitingClassObj, classObj
angular.module('App').classy.controller
name: 'BarCtrl'
inject: ['$scope']
someMethod: ->
@$scope.x = 12
angular.module('App').classy.controller
name: 'FooCtrl'
extend: 'BarCtrl'
inject: ['something']
someMethod2: ->
@$scope.y = something.get()
@someMethod()
@juangabreil
Copy link

I've updated your gist to add support to call superclass methods, by default it's called callParent but it can be configured in plugin options. Could you consider to update your gist?

BTW this solution is based on @jeresig's class.js

https://gist.github.com/juangabreil/af377b0f3e66d123bfd9

Regards

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