Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alxndrkalinin/1754572f8c5c770cf6a7b8a6272c9e18 to your computer and use it in GitHub Desktop.
Save alxndrkalinin/1754572f8c5c770cf6a7b8a6272c9e18 to your computer and use it in GitHub Desktop.
CoffeeScript Base Classes for AngularJS
module.exports = class BaseCtrl
@register: (module, name) ->
name ?= @name || @toString().match(/function\s*(.*?)\(/)?[1]
module.controller name, @
@inject: (annotations...) ->
ANNOTATION_REG = /^(\S+)(\s+as\s+(\w+))?$/
@annotations = annotations.map (annotation) ->
match = annotation.match(ANNOTATION_REG)
name: match[1], identifier: match[3] or match[1]
@$inject = @annotations.map (annotation) -> annotation.name
constructor: (dependencies...) ->
if dependencies.length
for annotation, index in @constructor.annotations
@[annotation.identifier] = dependencies[index]
@initialize?()
module.exports = class BaseService
@register: (module, name) ->
name ?= @name || @toString().match(/function\s*(.*?)\(/)?[1]
module.service name, @
# inject the list of dependencies
@inject: (annotations...) ->
ANNOTATION_REG = /^(\S+)(\s+as\s+(\w+))?$/
# annotations.unshift '$scope' if not '$scope' in args
@annotations = annotations.map (annotation) ->
match = annotation.match(ANNOTATION_REG)
name: match[1], identifier: match[3] or match[1]
@$inject = @annotations.map (annotation) -> annotation.name
constructor: (dependencies...) ->
if dependencies.length
for annotation, index in @constructor.annotations
@[annotation.identifier] = dependencies[index]
@initialize?()
class ExampleController extends BaseCtrl
@register()
@inject "$http", "$q"
initialize: ->
console.log "Example Controller Ready"
ExampleService : AngularService
class Exampleervice extends BaseService
@register 'ExampleService'
initialize: ->
console.log "Example Service Ready"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment