我想获取数据来更新我的表达式 {{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();
}
}
}]);
但如果我这样做,它就会起作用 http://pastebin.com/T7rjKYds ,我在 Controller 中而不是在我的服务中运行 .success
。
最佳答案
服务和工厂独立于作用域。他们无权通过依赖注入(inject)访问 $scope
以确保适当的关注点分离。
您有两个选择,将 $scope
传递给您的 getTopicContent.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);
}
}
}]);
或者返回 promise 并在 Controller 中添加 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();
}
}
}]);
关于javascript - 如何将 $scope 传递给服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27307985/