lucassus / angular-coffee-seed

AngularJS seed based on grunt JavaScript tasks runner and bower a package manager for the web

Home Page:http://lucassus-angular-seed.herokuapp.com/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Try BaseCtrl

lucassus opened this issue · comments

http://www.devign.me/angular-dot-js-coffeescript-controller-base-class

# 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 = ""