我正在尝试使用$ http方法从JSON API中提取数据,但是AngularJS不断抛出$ http未定义的错误,即使它已在控制器中定义。
控制器:
app.controller("CompaniesController", ['$scope', '$http', 'companyService', function($scope, $http, companyService) {
$scope.title = 'Companies';
$scope.title_sub = 'Add Company';
$scope.add = function(newCompany) {
companyService.addCompany( {
id: newCompany.id,
name: newCompany.name,
primary_contact: newCompany.primary_contact,
address: newCompany.address,
function: newCompany.function,
telephone: newCompany.phone,
fax: newCompany.fax,
url: newCompany.url
});
};
$scope.companies = companyService.getCompanies();
}]);
服务:
app.service('companyService',[function(){
var companies = [];
return {
addCompany: function(company){
companies.push(company);
},
getCompanies: function(){
$http({method: 'GET', url: '/api/example/view/4553'}).success(function(data) {
var companies = data; // response data
});
return companies;
}
}
}]);
答案 0 :(得分:5)
您应该将$http
注入“companyService”服务,如此
app.service('companyService',['$http', function($http){
...
顺便说一下,您可以将它从'CompaniesController'中删除,因为您不直接在那里使用它。