Vladimir Djukic
Vladimir Djukic

Reputation: 2072

Using factory inside route controller

I have factory like this:

angular.module('commentsApp')
        .factory("getCommentsFactory", getCommentsFactory);

function getCommentsFactory(scope, $http)
{
    return {
        getComments: getComments
    };

    function getComments()
    {
        return $http.get("/api/comments/" + scope.param)
                .then(getCommentsComplete)
                .catch(getCommentsFailed);

        function getCommentsComplete(data) {
        //GET ALL USER AND COMMENTS TOGETHER
            return data;
        }

        function getCommentsFailed(error) {
            scope.setLoading(false);
            return error;
        }
    }

}

When I try to call this factory from my contrller like this:

.controller('CommentsCtrl',function($scope,$http,$routeParams,getCommentsFactory){
              $scope.param = $routeParams.id;
              $scope.comments = [];
              getCommentsFactory.getComments()
                      .then(function(data){
                          console.log(data);
              });
...

I get error:

Error: [$injector:unpr] http://errors.angularjs.org/1.4.3/$injector/unpr?p0=scopeProvider%20%3C-cope%20%3C-%20getCommentsFactory at Error (native) at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:6:416 at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:40:375 at Object.d [as get] (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:38:364) at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:40:449 at d (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:38:364) at Object.e [as invoke] (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:39:124) at Object.$get (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:37:98) at Object.e [as invoke] (https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:39:156) at https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:40:478

Anyone know what is problem?

Upvotes: 0

Views: 76

Answers (1)

masimplo
masimplo

Reputation: 3774

Problem is you are injecting something called "scope" in your factory, but there is no scope you can inject there.

If you need a value from your controller there you should pass it as a parameter in the function. You cannot inject a controller scope in a factory.

Upvotes: 2

Related Questions