Leon Leon - 3 months ago 11
AngularJS Question

AngularJS - use custom service within controller

What is the correct way to inject a service into a controller in Angular?

I have written a service and i’d like to use it in my controllers. But i keep getting an error. Maybe it would be easy for someone to spot my mistake…

authController.js

(function() {

'use strict';

angular
.module('authApp')
.service('authService', function($auth, $state, $http, $rootScope, envService, $scope) {
// some code
})
.controller('SignupController', SignupController, ['$scope', 'authService’]);

function SignupController($http, $scope, $rootScope, $location, envService, authService) {
// want to use my authService here
}

...


At this point I get the following error :


angular.js:12477 Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- authService


What is wrong with the way I have injected authService into my signupController??

Thanks.

Answer

You have an error declaring your controller. Declaring a controller with the array syntax receives the name of the controller as a String as first parameter, and an array as a second parameter. The last element of the array must be the a function with all the controller logic. That function must have as many parameters as previous elements in the array itself. In your case it should be something like:

(function() {

'use strict';

angular
       .module('authApp')
       .service('authService', function($auth, $state, $http, $rootScope, envService,   $scope) {
          // some code 
        })
       .controller('SignupController', ['$http', '$scope', '$rootScope', '$location', 'envService', 'authService',  function ($http, $scope, $rootScope, $location, envService, authService) {
          // Use your authService here 
       }]);
 ...
Comments