服务 - optionService.js
控制器 - app.js& welcomeCtrl.js& otherCtrl.js
app.js
var app = angular.module('mainapp', ['mainapp.welcome','optionServiceModule']);
app.controller('mainappCtrl', function ($scope,optionService) {
optionService.fetchOptionDetails().success(function(response){
$scope.option = response;
});
});
welcomeCtrl.js
var app = angular.module('mainapp.welcome', ['optionServiceModule']);
app.controller('welcomeCtrl',[function($scope,optionService) {
optionService.fetchOptionTwoDetails().success(function(response){
$scope.OptionTwo = response;
});
}]);
optionService.js
var app = angular.module('optionServiceModule',[]);
app.factory('optionService',['$http',function($http) {
var obj = {};
obj.fetchOptionDetails = function(){
return $http.get('localhost/api/option/optionOne');
}
obj.fetchOptionTwoDetails = function(){
return $http.get('localhost/api/option/optionTwo');
}
return obj;
}]);
optionService在app.js中运行正常但是 在WelcomeCtrl.js中给出错误
错误
Cannot read property 'fetchOptionTwoDetails' of undefined
想知道如何在多个控制器文件中使用服务吗?
先谢谢你
答案 0 :(得分:2)
将$scope
和optionService
作为字符串注入控制器
app.controller('welcomeCtrl',['$scope','optionService',function($scope,optionService) {
optionService.fetchOptionTwoDetails().success(function(response){
$scope.OptionTwo = response;
});
}]);
答案 1 :(得分:1)
Js代码
var app1 = angular.module('mainapp.welcome', ['optionServiceModule']);
app1.controller('welcomeCtrl', function($scope, optionService) {
optionService.fetchOptionTwoDetails().success(function(response) {
$scope.OptionTwo = response;
});
});
您添加了[]但忘了添加依赖