我正在尝试将服务注入控制器,我收到以下错误:
Error: [$injector:unpr] Unknown provider: employeeServiceProvider <- employeeService
http://errors.angularjs.org/1.3.0-beta.17/$injector/unpr?p0=employeeServiceProvider%20%3C-%20employeeService
at http://localhost:9082/angularJSDemo/js/lib/angular.js:78:12
at http://localhost:9082/angularJSDemo/js/lib/angular.js:3894:19
at Object.getService [as get]
以下是plunker代码。任何帮助将不胜感激。
答案 0 :(得分:18)
你正在重复angular.module('demoApp', [])
它将清除附加到已经添加的模块的任何实体并重新创建模块,在模块初始化之后你应该使用它的引用或者只使用angular.module('demoApp').service...
使用它将检索您可以添加服务的模块等...
var module = angular.module('demoApp', []).controller('employeeController', function($scope, employeeService) {
$scope.employees = employeeService.getData();
});
module.factory('employeeService', function (){
return {
getData : function(){
var employees = [{name: 'John Doe', id: '1'},
{name: 'Mary Homes', id: '2'},
{name: 'Chris Karl', id: '3'}
];
return employees;
}
};
});
<强> Demo 强>
注意使用angular.module('myModule',[])将创建模块myModule并覆盖任何名为myModule的现有模块。使用angular.module('myModule')来检索现有模块。
答案 1 :(得分:3)
我不知道您重复创建模块(demoApp)的原因。在第6行,您试图创建demoApp模块,这是导致问题的原因。您的代码应如下所示:
angular.module('demoApp', [])
.controller('employeeController', function($scope, employeeService) {
$scope.employees = employeeService.getData();
})
.factory('employeeService', function (){
return {
getData : function(){
var employees = [{name: 'John Doe', id: '1'},
{name: 'Mary Homes', id: '2'},
{name: 'Chris Karl', id: '3'}
];
return employees;
}
};
});
或者
var demoApp=angular.module('demoApp', [])
.controller('employeeController', function($scope, employeeService) {
$scope.employees = employeeService.getData();
});
demoApp.factory('employeeService', function (){
return {
getData : function(){
var employees = [{name: 'John Doe', id: '1'},
{name: 'Mary Homes', id: '2'},
{name: 'Chris Karl', id: '3'}
];
return employees;
}
};
});
而不是
angular.module('demoApp', []).controller('employeeController', function($scope, employeeService) {
$scope.employees = employeeService.getData();
});
angular.module('demoApp', []).factory('employeeService', function (){
return {
getData : function(){
var employees = [{name: 'John Doe', id: '1'},
{name: 'Mary Homes', id: '2'},
{name: 'Chris Karl', id: '3'}
];
return employees;
}
};
});
如果你想将你的控制器保存在一个单独的文件中(这是推荐的),你可以考虑将此类文件作为你的abcController.js
angular.module('demoApp', ['demoApp.employeeController']).controller('employeeController', function($scope, employeeService) {
$scope.employees = employeeService.getData();
});
和xyzService.js
angular.module('demoApp.employeeController', []).factory('employeeService', function (){
return {
getData : function(){
var employees = [{name: 'John Doe', id: '1'},
{name: 'Mary Homes', id: '2'},
{name: 'Chris Karl', id: '3'}
];
return employees;
}
};
});