0

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.

2
  • 1
    $scope isn't injectable in service, also you have messed SignupController controller DI array and sequence in controller function Commented Sep 3, 2016 at 16:35
  • Ah that makes a lot of sense about $scope! >.< Commented Sep 3, 2016 at 16:45

2 Answers 2

1

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 
       }]);
 ...
Sign up to request clarification or add additional context in comments.

Comments

0

You can check the styleguide to write your controllers, services and inject your dependencies in a better way.

1 Comment

I'm aware of the documentation, but I don't really know what i'm looking for. Hence the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.