我正在尝试将工厂应用程序注入ApplicationService工厂。两者都在同一模块中定义。
应用程序工厂(application.model.js)
(function(Object, coreModule) {
'use strict';
// the factory to expose that allows the creation of application instances
var ApplicationFactory = function() {
console.log("Application factory!");
return {foo: 'bar'};
}
coreModule.factory('Application', [ApplicationFactory]);
})(Object, angular.module('core'));
ApplicationService工厂(application.service.js)
(function(coreModule) {
'use strict';
var ApplicationService = function(Application) {
var api = {
shout = function() {console.log(Application);}
};
return api;
}
ApplicationService.$inject = ['Application'];
coreModule.factory('ApplicationService', [ApplicationService]);
})(angular.module('core'));
然后我将ApplicationService工厂注入控制器并调用方法shout。我在控制台的日志中未定义,应用程序始终未定义。如果在控制器中,我可以使用它。所以我知道两个工厂都是独立工作的。 这两个文件都在我的index.html中导入。
我花了好几个小时寻找这个问题,但我找不到它。我做错了什么?
答案 0 :(得分:2)
请参阅下面的工作演示。
您有两个选择。
a)删除方括号:
coreModule.factory('ApplicationService', ApplicationService)
b)在ApplicationService之前添加注入的Application作为第一个元素:
coreModule.factory('ApplicationService', ['Application', ApplicationService])
var app = angular.module('core', []);
app.controller('firstCtrl', function($scope, ApplicationService) {
ApplicationService.shout();
});
(function(Object, coreModule) {
'use strict';
// the factory to expose that allows the creation of application instances
var ApplicationFactory = function() {
console.log("Application factory!");
return {
foo: 'bar'
};
};
coreModule.factory('Application', [ApplicationFactory]);
})(Object, angular.module('core'));
(function(coreModule) {
'use strict';
var ApplicationService = function(Application) {
var api = {
shout: function() {
console.log(Application);
}
};
return api;
};
ApplicationService.$inject = ['Application'];
coreModule.factory('ApplicationService', ApplicationService);
})(angular.module('core'));

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="core">
<div ng-controller="firstCtrl">
</div>
</body>
&#13;