Why do they pass arrays to AngularJS?

Consider this snippet from Brad Green 's AngularJS .

var directives = angular.module('guthub.directives', []); directives.directive('butterbar', ['$rootScope', function ($rootScope) { return { link: function (scope, element, attrs) { element.addClass('hide'); $rootScope.$on('$routeChangeStart', function () { element.removeClass('hide'); }); $rootScope.$on('$routeChangeSuccess', function () { element.addClass('hide'); }); } }; }] ); directives.directive('focus', function () { return { link: function (scope, element, attrs) { element[0].focus(); } }; }); 

Note that for the butterbar directive, it goes into an array, where the first element is just a string with the dependency name "$rootScope" , and the second element is a function. This function declares a dependency on $rootScope . Why are we repeating here? Especially when it's possible to just do this:

 directives.directive('butterbar', function ($rootScope) { return { link: function (scope, element, attrs) { element.addClass('hide'); $rootScope.$on('$routeChangeStart', function () { element.removeClass('hide'); }); $rootScope.$on('$routeChangeSuccess', function () { element.addClass('hide'); }); } }; }); 

I assume that the dependency name, which is a string, has some meaning. Can someone tell me why they do this throughout the book (and not just for directives)?

+6
source share
1 answer

When JavaScript is minimized, parameter names often change to something shorter, like a . This will break the dependency injection.

If you use an array, Angular knows what to enter and where to enter it. This works with an array because the string elements of the array are not modified by minification.

In this example:

 app.controller('test', function( $scope, $someProvider ) { }); 

The shortened code may look something like this:

 app.controller('test',function(a,b){}); 

This will no longer work, since Angular does not know what to enter, but at the same time:

 app.controller('test', ['$scope', '$someProvider', function( $scope, $someProvider) { }]); 

the abbreviated code may end as follows:

 app.controller('test',['$scope','$someProvider',function(a,b) {}]); 

This will work anyway, because Angular still knows what to type. See the note on minimization in the Angular tutorial .

Usually I just add an array style when I'm ready for production.

+13
source

Source: https://habr.com/ru/post/956660/


All Articles