Writing Angular factory with CoffeeScript Class style


Recently I am trying to learn AngularJs and CoffeeScript by writing a small app.
After reading some blogs I can write Angular controller and service with CoffeeScript Class style. The following is a example of controller.

libr = angular.module('libr.controllers.main', [])
class MainController
  @$inject: ['$scope']
  constructor: (@$scope) ->
    @$scope.test = test
  test: ()->
    console.log 'Hello'
libr.controller 'MainCtrl', MainController

And it works well.

But I can't convert a Angular factory as following successfully with using Coffee Class style.

var app = angular.module('app', ['ngResource', 'ngRoute']);

// Some APIs expect a PUT request in the format URL/object/ID
// Here we are creating an 'update' method 
app.factory('Notes', ['$resource', function($resource) {
  return $resource('/notes/:id', null,
          'update': { method:'PUT' }

This code is a example code from AngularJs official website:http://docs.angularjs.org/api/ngResource.$resource

Could anyone help me to convert it to CoffeeScript Class style?

Problem courtesy of: Junv


There's so little code in that factory, I don't really understand the point of making it a Class.

app = angular.module("app", ["ngResource", "ngRoute"])

app.factory "Notes", ["$resource", ($resource) ->
    $resource("/notes/:id", null, { update: { method: "PUT" } })

But having said that, if you want to use coffeescript classes for services in general (it doesn't work well with factories since they're singletons), you can do something like this:

class Foo
  constructor: ($someDependency) ->
    @myVar = "hello"

  bar: ->
    console.log @myVar

app.service("Foo", ['$someDependency', Foo])
Solution courtesy of: Adam Albrecht


class Notes
  url = "/notes/:id"
  constructor:(@$resource) ->
    return $resource url, {id: "@id"}, { update: {method: "PUT"} } 

angular.module("app").factory "Notes", ["$resource", Notes]
Discussion courtesy of: Vipous

This recipe can be found in it's original form on Stack Over Flow.