在另一家工厂AngularJS内使用工厂

时间:2014-04-16 16:56:37

标签: javascript angularjs angularjs-factory angularjs-module

我有一个模块......

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?

2 个答案:

答案 0 :(得分:20)

这就是我要做的事情:

在工厂一

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;
        }
    ]);

答案 1 :(得分: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' }
        });
    });