Home > Development > Angular Services in CoffeeScript

Angular Services in CoffeeScript

This jsbin demonstrates how to use a CoffeeScript class to implement an Angular Service, using Service, Factory and Provider styles. You may have to click “Run with JS” to update Output pane. Download gist from github.

Update: by itself this is not enough, since services usually have to inherit other resources, and look something like this:

.service('thumbService', ['$log', '$q', ($log, $q) ->

A working example (using .factory instead of .service) from the angular-grunt-coffeescript seed app:

Example of a service shared across views.
Wrapper around the data layer for the app. 
name = 'common.services.dataSvc'

class DataSvc

	constructor: (@$log, @$http, @env) ->

	_get: (relPath)->
		return @$http.get("#{@env.serverUrl}/#{relPath}")

	getPeople: () ->
		return @_get('people')

	getPerson: (id) ->
		return @_get("person/#{id}")

angular.module(name, []).factory(name, ['$log','$http', 'common.services.env', ($log, $http, env) ->
	new DataSvc($log, $http, env)
  1. May 11th, 2014 at 15:13 | #1

    hi peterk thank’s for this article,
    I’m currently writing https://github.com/ranska/rang https://github.com/ranska/aether who is a little lib focus on coffee script class layer for angular. I try to find people who can tell me if there is thing’s they like, want to be add or remove from it.
    Could you please give me your point of view on it.

  1. No trackbacks yet.