Reputation: 10692
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
}]);
Upvotes: 0
Views: 89
Reputation: 4849
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
Upvotes: 1