Pregunta

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 
});
¿Fue útil?

Solución

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)

Otros consejos

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top