Skip to content

Instantly share code, notes, and snippets.

@duanefields
Last active June 8, 2016 00:55
Show Gist options
  • Save duanefields/ff4303c8e49ab5df2664 to your computer and use it in GitHub Desktop.
Save duanefields/ff4303c8e49ab5df2664 to your computer and use it in GitHub Desktop.
CoffeeScript Base Classes for AngularJS
module.exports = class AngularController
# register the subclass with angular, module and name are optional
@register: (name, module) ->
module ?= @module || angular.module 'controllers'
name ?= @name || @toString().match(/function\s*(.*?)\(/)?[1]
module.controller name, @
# inject the list of dependencies, as a list of Strings
@inject: (args...) ->
@$inject = args
constructor: (args...) ->
for key, index in @constructor.$inject
# makes injected services to instance vars
@[key] = args[index]
@initialize?()
module.exports = class @AngularService
# register the subclass with angular, module and name are optional
@register: (name, module) ->
name ?= @name || @toString().match(/function\s*(.*?)\(/)?[1]
module ?= @module || angular.module 'services'
module.service name, @
# inject the list of dependencies
@inject: (args...) ->
args.unshift '$scope' if not '$scope' in args
@$inject = args
constructor: (args...) ->
# assign injected services to instance vars
for key, index in @constructor.$inject
@[key] = args[index]
@initialize?()
class ExampleController extends AngularController
@register()
@inject "$http", "$q"
initialize: ->
console.log "Example Controller Ready"
ExampleService : AngularService
class LinkedInService extends AngularService
@register 'LinkedInService'
initialize: ->
console.log "Example Service Ready"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment