0

Please see below, are those 2 samples of dependency injection basically equal in what they are doing or have I missed something important in my life?

Code sample #1

angular.module("app", []);
function Controller($scope, SomeService) {
   // do stuff
}

Controller.$inject = ['$scope', 'SomeService'];    

Code sample #2

angular.module("app", [])
.controller("Controller", [ '$scope', 'SomeService' function($scope, SomeService){
    // do stuff
}]);
1
  • @musically_ut - thanks - that was a typo Commented Nov 20, 2013 at 21:34

1 Answer 1

1

These two pieces of code are not the same.

angular.module("app", []);
function Controller($scope, SomeService) {
   // do stuff
}

Controller.$inject = ['$scope', 'SomeService'];    

Does not add the controller into the module (namespace) app though it does declare that the app module exists. Also, I do not think that this code will run. See below for how to use this style of injection.

angular.module("app", [])
.controller("Controller", [ '$scope', 'Service' function($scope, SomeService){
    // do stuff
}]);

The second form uses the shorthand .controller() method to create the controller and inject the resources. You can then angular.module('app') to pull a reference to the named controller.

To manually inject into a controller follow this style:

angular.module('app', [])
  .factory('someService', function($window) {
    return {
      serve: function(text) {
        $window.alert(text);
      }
    };
  });

var injector = angular.injector(['app', 'ng']);

function Controller($scope, someService) {
  $scope.doStuff = function() {
    someService.serve('Doing stuff');
  };
}

injector.instantiate(Controller);

For a complete example see: http://docs.angularjs.org/guide/di

Sign up to request clarification or add additional context in comments.

5 Comments

Good point, but my question was regarding the Controller.$inject & dependency injection
oh, then they are the same. Both are safe from minification errors.
I am looking at this a little closer. I don't use the first syntax and I want to be sure it is correct
Better answer coming up. Give me a minute
As opposed to using the Module("app").directive() Module.service, etc... Builder pattern that is typically how you put components together. It is safer for minification and its a much more readable and less error prone. See: docs.angularjs.org/guide/module If you read the dependency injection link above, you will see that DI is actually complicated but that complexity is largely hidden when you use the Module helper methods

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.