2014-12-05 122 views
1

我想获取数据来更新我的表达式{{myList}},但似乎我的服务中存在$ scope问题,下面的代码似乎不起作用:

app.controller('AppCtrl', ['$scope', 'getTopicContent', function($scope,getTopicContent){ 
    getTopicContent.request(); 

}]); 

app.factory('getTopicContent', ['$http', function($http, $scope){ 

    var query = function() { 
     return $http({ 
      url: "http://www.corsproxy.com/mydata.me/level1/list.php", 
      method: "GET" 
     }).success(function(data, $scope){ 
      $scope.myList= data; 
     }); 
    } 

    return { 
     request : function(){ 
      return query(); 
     } 

    } 
}]); 

但是,如果我这样做,它会工作,我运行。 success而不是我的服务。

+0

变化'应用。工厂('getTopicContent',['$ http','$ scope',函数($ http,$ scope)' – RandomUser 2014-12-05 03:07:32

+0

@RandomUser我在它不工作之前试过了,它表示Unknown provider:$ scopeProvider < - $ scope < - getTopicContent – mike19911 2014-12-05 03:17:27

回答

2

服务和工厂是独立的范围。他们无法通过依赖注入访问$scope以确保正确分离关注点。

你有两个选择,通过$scopegetTopicContent.request($scope)方法是这样的:

app.controller('AppCtrl', ['$scope', 'getTopicContent', function($scope,getTopicContent){ 
    getTopicContent.request($scope); 
}]); 

app.factory('getTopicContent', ['$http', function($http){ 

    var query = function($scope) { 
     return $http({ 
      url: "http://www.corsproxy.com/mydata.me/level1/list.php", 
      method: "GET" 
     }).success(function(data){ 
      $scope.myList = data; 
     }); 
    } 

    return { 
     request : function($scope){ 
      return query($scope); 
     } 

    } 
}]); 

还是回到了承诺,并添加控制器,而不是内部的success()处理程序:

app.controller('AppCtrl', ['$scope', 'getTopicContent', function($scope,getTopicContent){ 
    getTopicContent.request().success(function(data){ 
     $scope.myList = data; 
    }); 
}]); 


app.factory('getTopicContent', ['$http', function($http){ 

    var query = function() { 
     return $http({ 
      url: "http://www.corsproxy.com/mydata.me/level1/list.php", 
      method: "GET" 
     }) 
    } 

    return { 
     request : function(){ 
      return query(); 
     } 

    } 
}]); 
+0

我认为第二个选项更清洁,你觉得怎么样? – mike19911 2014-12-05 03:47:26

+0

如果我想在$ state中运行我的服务,该怎么办? – mike19911 2014-12-05 03:47:48

+0

有一点要补充的是,你永远不会把范围传递给服务。它始终是访问服务的范围,而不是其他方式。就像@Sly_cardinal所说的那样,你可以将范围变量作为参数传递给你的服务并对其执行操作,但是你的服务并不总是可以访问范围。 – justinpinili 2014-12-05 03:49:08

相关问题