Skip to content

Instantly share code, notes, and snippets.

@saystone
Forked from lucassus/BaseCtrl.coffee
Last active August 29, 2015 14:18
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 saystone/5ad66cb933c61ebac00f to your computer and use it in GitHub Desktop.
Save saystone/5ad66cb933c61ebac00f to your computer and use it in GitHub Desktop.
class @BaseCtrl
@register: (app, name) ->
name ?= @name || @toString().match(/function\s*(.*?)\(/)?[1]
app.controller name, this
@inject: (annotations...) ->
ANNOTATION_REG = /^(\S+)(\s+as\s+(\w+))?$/
@annotations = _.map annotations, (annotation) ->
match = annotation.match(ANNOTATION_REG)
name: match[1], identifier: match[3] or match[1]
@$inject = _.map @annotations, (annotation) -> annotation.name
constructor: (dependencies...) ->
if dependencies.length
for annotation, index in @constructor.annotations
this[annotation.identifier] = dependencies[index]
@initialize?()
app = angular.module("myApp")
class FormCtrl extends BaseCtrl
@register app, "products.FormCtrl"
@inject "$scope", "$location", "alerts", "product as remote"
initialize: ->
@reset()
save: (product) ->
promise = product.$save()
successMessage = if product.persisted() then "Product was updated" else "Product was created"
promise.then =>
@alerts.success successMessage
@$location.path "/products"
reset: ->
@product = angular.copy(@remote)
@$scope.product = @product
delete: ->
promise = @product.$delete()
promise.then =>
@alerts.info "Product was deleted"
@$location.path "/products"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment