4

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?

2
  • "just met some issue" -- can you describe the issue? Commented Feb 12, 2014 at 17:57
  • Sorry for my unclear description. The issue is I can't convert the sample Angular factory to CoffeeScript Class style. Commented Feb 13, 2014 at 1:09

2 Answers 2

3

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])
Sign up to request clarification or add additional context in comments.

Comments

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


angular.module("app").factory "Notes", ["$resource", Notes]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.