map7
map7

Reputation: 5126

Angularjs accessing methods in another factory

I've got an AngularJS model in which I've created a module called myService to hold some commonly used code which I use throughout my application. My Common factory is where I've been adding all my methods and now I want to split this up and give them good names.

A lot of my methods call each other so how can I call a method which is in another factory?

angular.module('myService', ['ngResource'])
  .factory('test2', ($window) ->
    return {
      foobar: () ->
        Common.test()
    }
  )  
  .factory('Common', ($window) ->
    return {
      test: () ->
        alert 'testing'
    }
  )

Upvotes: 4

Views: 4742

Answers (2)

Sacky San
Sacky San

Reputation: 1672

This is what i did and worked fine. Call SessionPresenters from Session. You need to pass the SessionPresenters as an argument to factory implementation function.

angular.module('tryme3App')
    .factory('Session', function ($resource, DateUtils, SessionPresenters) {
        return $resource('api/sessions/:id', {}, {
            'query': { method: 'GET', isArray: true},
            'get': {
                method: 'GET',
                transformResponse: function (data) {
                    data = angular.fromJson(data);

                    var result = SessionPresenters.get({id: data.id})
                    data.presenters = result; 
                    return data;
                }
            },
            'update': { method:'PUT' }
        });
    }).factory('SessionPresenters', function ($resource, DateUtils) {
        return $resource('api/session.Presenters/:id', {}, {
            'query': { method: 'GET', isArray: true},
            'get': {
                method: 'GET', isArray: true
            },
            'update': { method:'PUT' }
        });
    });

Upvotes: 0

Josh David Miller
Josh David Miller

Reputation: 120513

You only need to inject it:

.factory('test2', function (Common) {
  return {
    foobar: function () {
      Common.test();
    }
  };
})

Upvotes: 12

Related Questions