18

我有一个模块...

angular.module('myModule', []);

然后是工厂

angular.module('myModule')
.factory('factory1', [
  function() {
    //some var's and functions
}
]);

然后另一个工厂

angular.module('myModule')
.factory('factory2', [
  function() {
    //some var's and functions BUT I want to use some var's from factory1
}
]);

但是我想在 factory2 中使用 factory1 中的一些变量,如何将 factory1 注入 factory2?

4

2 回答 2

22

这就是我要做的:

在一号工厂

angular.module('sampleApp')
    .factory('factory1', function() {
        var factory1 = {};

        factory1.method1 = function () {
            return true;
        };

        factory1.method2 = function () {
            return "hello";
        };

        return factory1;
    }
);

在二厂

angular.module('sampleApp')
    .factory('factory2', ['factory1',
        function(factory1) {

            var factory2 = {};

            factory2.method3 = function () {
                return "bye vs " + factory1.method2();
            };

            return factory2;
        }
    ]);
于 2014-04-16T16:59:31.507 回答
1

这就是我所做的并且工作得很好。从 Session 调用 SessionPresenters

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' }
        });
    });
于 2016-02-15T03:12:01.703 回答