Object-Oriented AngularJS Service Example

I’ve seen some examples of using AngularJS services online that follow the convention of FooService.someMethod() or BarService.whateverElse(). I was confused about how to use AngularJS without throwing all my useful object-oriented programming experience out the window. I’ve come up with a solution that I think I like.

Here’s the CoffeeScript class. It’s simple enough that I think it should be fairly self-explanatory. Don’t worry too much about the details of what it does. Just notice there’s a constructor and one instance method.

"use strict"

angular.module("myApp").service "Report", (Payment) ->

  class Report
    constructor: ->
      @startDate = moment().subtract(14, "days").format("MM/DD/YYYY")
      @endDate   = moment().format("MM/DD/YYYY")

    refresh: (options) ->
      Payment.query
        "between[startDate]": moment(options.startDate).format("YYYY-MM-DD")
        "between[endDate]":   moment(options.endDate).format("YYYY-MM-DD")
        "repId":              options.repId
        "issueId":            options.issueId

Here’s how I’m using my Report class in a controller:

"use strict"

angular.module("myApp").controller "PaymentsCtrl", ($scope, Report) ->

  report           = new Report()
  $scope.startDate = report.startDate
  $scope.endDate   = report.endDate
  $scope.rep       = {}
  $scope.issue     = {}

  $scope.refreshReport = ->
    report.refresh(
      startDate: $scope.startDate
      endDate:   $scope.endDate
      repId:     $scope.rep.id
      issueId:   $scope.issue.id
    ).then (rows) -> $scope.rows = rows

  $scope.refreshReport()

Notice how I’m not doing something like ReportService.refresh(). To me, that wouldn’t make complete sense. It makes a lot more sense to me to instantiate report and then say report.refresh().

By the way, I discovered this post after coming up with my idea. Ben’s way is almost identical to mine, although I think my way is ever so slightly cleaner. But the fact that someone else is doing roughly the same thing is probably evidence that this idea isn’t totally retarded.