1

My service is working as expected in both cases but I don't understand the difference between these 2 syntaxes. Enlighten me please. The official documentation is not very explicit about this point.

Syntax A :

service.factory('Alert',['$rootScope', '$timeout', function($rootScope, $timeout) {
  //Do stuff
}]);

Syntax B :

service.factory('Alert', function($rootScope, $timeout) {
 //Do stuff 
});
1
  • 1
    Look at the Dependency Injection (DI) documentation. Especially the Inline Annotation subsection and Where can I use DI? section Commented Oct 24, 2013 at 16:29

2 Answers 2

4

They both provide the same functionality but Syntax A (inline bracket notation) allows for your code to be minified through a JavaScript minifier. Because Syntax A is a little longer than Syntax B (and violates the DRY principle), the most appropriate and probably only case you'd want to use it would be when you want to minify your code.

Since Angular infers the controller's dependencies from the names of arguments to the controller's constructor function, if you were to minify the JavaScript code for [the] PhoneListCtrl controller, all of its function arguments would be minified as well, and the dependency injector would not be able to identify services correctly.

See this page for more information (A Note on Minification)

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

Comments

0

I also found a third syntax in the documentation. It appears to be more proper than the "Syntax A" (array notation) and compatible with JavaScript minifier :

var service = angular.module('alertService', []);
var alertServiceFactory = function($rootScope, $timeout) {
 //Do stuff 
});
alertServiceFactory.$inject = ['$rootScope', '$timeout'];
service.factory('Alert', alertServiceFactory);

More info here : http://docs.angularjs.org/guide/dev_guide.services.managing_dependencies

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.