简体   繁体   中英

How do I pass $scope to service

I want to get data to update my expression {{myList}} but it seem like I have the $scope issue in my service, below code doesn't seem to work :

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();
        }

    }
}]);

But if I do like this it will work http://pastebin.com/T7rjKYds , which I run the . success in the controller instead of within my service.

Services and factories are independent of the scope. They don't have access to $scope through dependency injection to ensure proper separation of concerns.

You have two options, pass the $scope to your getTopicContent.request($scope) method like this:

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);
        }

    }
}]);

Or return the promise and add the success() handler inside the controller instead:

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();
        }

    }
}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM