mike19911
mike19911

Reputation: 101

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.

Upvotes: 1

Views: 115

Answers (1)

Sly_cardinal
Sly_cardinal

Reputation: 12993

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

    }
}]);

Upvotes: 2

Related Questions