Skip to content

Instantly share code, notes, and snippets.

@savage69kr
Forked from elado/AngularBaseCtrl.coffee
Created May 1, 2014 14:23
Show Gist options
  • Save savage69kr/2b787f609e11d0cbfd1e to your computer and use it in GitHub Desktop.
Save savage69kr/2b787f609e11d0cbfd1e to your computer and use it in GitHub Desktop.
# dependency - Function.prototype.bind or underscore/lodash
app = angular.module 'someApp'
class @BaseCtrl
@register: (app, name) ->
name ?= @name || @toString().match(/function\s*(.*?)\(/)?[1]
app.controller name, @
@inject: (args...) ->
@$inject = args
constructor: (args...) ->
for key, index in @constructor.$inject
@[key] = args[index]
for key, fn of @constructor.prototype
continue unless typeof fn is 'function'
continue if key in ['constructor', 'initialize'] or key[0] is '_'
@$scope[key] = fn.bind?(@) || _.bind(fn, @)
@initialize?()
app = angular.module 'someApp'
class BookFormCtrl extends BaseCtrl
@register app
# list of dependencies to be injected
# each will be glued to the instance of the controller as a property
# e.g. @$scope, @Book
@inject '$scope', 'Book'
# initialize the controller
initialize: ->
@$scope.book =
title: "Hello"
# automatically glued to the scope, with the controller instance as the context/this
# so usable as <form ng-submit="submit()">
# methods that start with an underscore are considered as private and won't be glued
submit: ->
@Book.post(@$scope.book).then =>
@$scope.book.title = ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment