Error: [$injector:unpr] when injecting services in a controller

I know similar questions about this error has been asked numerous times before in SO, and I have read the answers, but as far as I am able to see, my code is designed correctly. But it can't of course since I get this error .. My app has a few services and and a few controllers, and all of them work together apart from one specific service/controller for some reason. I have been able to strip down the code to a minimum, shown below. The error appears when the TestController is triggered from the view with .. ng-controller="TestController" ..and the error message in the Chrome console is:

Error: [$injector:unpr] http://errors.angularjs.org/1.2.15/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope%20%3C-%20Loyper at Error (native)..

I have been struggling with this for some time, and can't see that this service (Loyper) and controller (TestController) is defined otherwise than those that are working, in terms of injections. Any help will be appreciated.

var app = angular.module('testapp', [
"ngRoute",
"mobile-angular-ui"

]);

app.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider) {
$routeProvider.
when('/', {
    templateUrl: 'main.html',
    controller: 'TestController'
}).
when('/loyper', {
    templateUrl: 'loyper.html',
    controller: 'LoypeController'
}).
otherwise({
    redirectTo: '/'
});

$httpProvider.defaults.useXDomain = true;

}]);

app.service('Loyper', ['$scope', '$http', function($scope, $http) {

var cached = false;
var loyper = {};
var message;

return {
    foo: 'bar'
}

}]);

app.controller('TestController', ['$scope', 'Loyper', function($scope, Loyper) {

angular.extend($scope, {
    getLoyper: function() {
        return Loyper.foo;
    }

});

$scope.loypelist = $scope.getLoyper();

}]);

Upvotes: 3

Views: 1976

Answers (1)

JB Nizet
JB Nizet

Reputation: 691775

A service can't be injected with $scope, since a service is a singleton, whereas each controller, and many directives, have their own scope. The problem is thus at this line:

app.service('Loyper', ['$scope', '$http', function($scope, $http) {

which should be

app.service('Loyper', ['$http', function($http) {

And in fact, since your service doesn't use $http, it shouldn't take $http as argument either.

Upvotes: 5

Related Questions