如何将$scope传递给服务

How do I pass $scope to service

本文关键字:服务 scope      更新时间:2023-09-26

我想获取数据来更新我的表达式{{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 工作,我运行.success控制器中,而不是在我的服务中。

服务和工厂与范围无关。他们无法通过依赖关系注入来访问$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 并在控制器中添加 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();
        }
    }
}]);