scotch / angular-brunch-seed

AngularJS + Brunch
Other
228 stars 78 forks source link

Example of using services.coffee #57

Closed christianjunk closed 11 years ago

christianjunk commented 11 years ago

Could you please provide me with an example on how to use services.coffee and on how to correctly inject a service into a controller.

Much thanks in advance, Christian

kylefinley commented 11 years ago

Here's an example of using a service.

You can inject services into a a control by passing a list containing strings -- representing the services -- and ending with a function that take the services as arguments.

For example:

angular.module('app.controllers', [])

.controller('AppCtrl', [
  '$scope'
  '$location'
  '$resource'
  '$rootScope'

($scope, $location, $resource, $rootScope) ->
  #...
])

To make this more clear this translates to:

angular.module('app.controllers', [])
  .controller('AppCtrl', [
    '$scope', '$location', '$resource', '$rootScope', function($scope, $location, $resource, $rootScope) {
       // ...
    }
    ]);

Does that help at all?

kylefinley commented 11 years ago

I updated my response, I was mistakenly showing an example of a directive.

christianjunk commented 11 years ago

Hi Kyle,

thank you for your response. Regarding to your answer I tried the following and it is working now. But could you please take a look at what I did and tell me if I am doing it in the right way ;) ?

1) I defined a service in the file services.coffee

### Sevices ###

angular.module("app.services", [])

.factory("version", ->
  "0.1"
)

.factory "events", ->
  EventService = {}
  list = []

  EventService.getItem = (index) ->
    list[index]

  EventService.addItem = (item) ->
    console.debug "Item added in Event service"
    list.push item

  EventService.removeItem = (item) ->
    list.splice list.indexOf(item), 1

  EventService.getItems = ->
    list

  EventService.size = ->
    list.length

  EventService

2) I added app.services to the file controllers.coffee. I am not sure about this. But when I do not add the app.service it doesn't work ...

### Controllers ###

angular.module('app.controllers', [
  # require the 'app.service' module
  'app.services'
])

.controller('AppCtrl', [
  '$scope'
  '$location'
  '$resource'
  '$rootScope'

3) After that I added the service to my services arguments list

.controller('TodoCtrl', [
  '$scope'
  'events'

($scope, events) ->

  $scope.eventService = events
  $scope.eventService.items = events.getItems()

Best regards, Christian

kylefinley commented 11 years ago

I think you've got it :) Let me know if you have any other questions