我试图将我的服务文件放在另一个js文件中,但收到错误
Unknown provider: $scopeProvider <- $scope <- getData
我创建了3个文件:
app.js
app=angular.module('myApp', []); console.log("app.js loaded.");
service.js
app.service('getData',['$scope','$http',function($scope,$http){
this.getDataFrom = function(){
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function(response) {$scope.names = response.records;});
}; }]); console.log("script loaded.");
的index.html
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js"></script><script src="app.js"></script><script src="service.js"></script>
<script>app.controller('customersCtrl',['$scope','getData', function($scope, getData) {
alert(getData.getDataFrom());}]);</script>
基本上我试图将this代码放在不同的文件中。
答案 0 :(得分:1)
您无法将范围注入服务。它没有那样工作,因为它们与范围无关。
尝试按如下方式重写代码:
删除服务和注入中的$ scope引用,并返回$ http.get的结果,这是一个承诺
app.service('getData',['$http',function($http){
this.getDataFrom = function(){
return $http.get("http://www.w3schools.com/angular/customers.php")
}; }]); console.log("script loaded.");
然后,更改您的控制器以使用该服务,并在获取数据时更新其范围:
<script>app.controller('customersCtrl',['$scope','getData','commentDataService', function($scope, getData,commentDataService) {
commentDataService.getComments().then(function(data) {
$scope.data = data;
console.log('the data is here!', data);
});
alert(commentDataService.getComments());
alert(getData.getDataFrom());}]);</script>
答案 1 :(得分:0)
您不能在服务中注入$ scope。所以你的服务应如下所示:
app.service('getData',['$http',function($http){
var names = null;
this.getDataFrom = function(){
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function(response) {names = response.data.records; return names;});
}; }]);
答案 2 :(得分:0)
我得到了它并通过此信息的帮助获取数据“$ scope与范围无关” 最后用这段代码获得数据:
service.js
app.service('getData',['$http',function($http){
this.getDataFrom = function(){
return $http.get("http://www.w3schools.com/angular/customers.php")
.then(function(response) {
return response.data.records;
});
};}]);
的index.html
app.controller('customersCtrl', ['$scope', 'getData', function($scope, getData) {
getData.getDataFrom().then(function(response){
alert(JSON.stringify(response));
$scope.names=response;
});
}]);