Zoneh
Zoneh

Reputation: 192

How to call factory/service from controller in AngularJS? error: Unknown Provider error in component $injector

I'm developing a mobile app with AngularJS. First I called all $http requests inside a controller as I would usually do. Now that I've read more about Angular I've seen that that may not be the best practice, especially if you want to share data between controllers. So i'm now reinventing my controller/service system.

Now to the problem. I'm calling a service from the controller, but I'm getting an error: Unknown Provider error in component $injector

Could anyone help me?

The codez:

listdnModule.factory('getActiveDnService', function ($scope, $http) {
    return {
            getActiveDnSvc: function (id) {
                return $http({
                    method: 'POST', url: 'svc.aspx/getActiveDN', data: "{'id':" + id + "}", cache: true
                });
            }
    };
});

listdnModule.controller('listdnCtrl', ['$scope', '$http', 'getActiveDnService', function ($scope, $http, svc) {
    $scope.mjav = 1;
    svc.getActiveDnSvc($scope.mjav).success(function (data) {
        $scope.listdn = data.d;
    });
}]);

Upvotes: 0

Views: 2389

Answers (1)

ms87
ms87

Reputation: 17492

Remove $scope from the injected dependencies of the service, $scope can only be injected to controllers, and passed in as parameters of link functions of directives in angular. Your service shoule look like:

listdnModule.factory('getActiveDnService', function ($http) {
    return {
            getActiveDnSvc: function (id) {
                return $http({
                    method: 'POST', url: 'svc.aspx/getActiveDN', data: "{'id':" + id, cache: true
                });
            }
    };
});

Upvotes: 3

Related Questions