Skip to content

Instantly share code, notes, and snippets.

@cemeng
Created October 4, 2012 00:29
Show Gist options
  • Save cemeng/3830781 to your computer and use it in GitHub Desktop.
Save cemeng/3830781 to your computer and use it in GitHub Desktop.
Angular Service and Factory
class @JobInvoice
  constructor: (preloadedInvoice) ->
    angular.extend(this, preloadedInvoice)
    @saveURL = "/job_invoices/update/#{@id}.json"
  subTotal: ->
    @items.
      map((i) -> i.quantity * i.unit_price).
      reduce ((sum, price) -> sum + price), 0
  addItem: (item) ->
    @items.push angular.copy item
  toServerFormat: ->
    { job_invoice: { status: @status, notes: @notes, items_attributes: @items } }

app.service "invoice", JobInvoice
# this is totally awesome!
app.factory "invoice", (preloadedInvoice) ->
  invoice = preloadedInvoice
  invoice.saveURL = "/job_invoices/update/#{invoice.id}.json"
  invoice.subTotal = ->
    @items.
      map((i) -> i.quantity * i.unit_price).
      reduce ((sum, price) -> sum + price), 0
  invoice.addItem = (item) ->
    @items.push angular.copy item
  invoice.toServerFormat = ->
    { job_invoice: { status: @status, notes: @notes, items_attributes: @items } }
  invoice
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment