Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do they pass arrays all over in AngularJS?

Consider this snippet from AngularJS by Brad Green.

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();
        }
    };
});

Notice that for the "butterbar" directive he passes in an array where the first item is just a string with the dependency name "$rootScope", and the second item is a function. That function declares a dependency on $rootScope. Why do we repeat ourselves here? Especially when it appears to be 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'm guessing that the dependency name being a string has some sort of significance. Can anyone tell me why they do this throughout the book (and not just for directives)?

like image 538
Chev Avatar asked Oct 24 '13 17:10

Chev


1 Answers

When JavaScript is minified, the names of parameters are often changed to something shorter such as a. This would break dependency injection.

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

In this example:

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

minified code might look something like this:

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

This would no longer work since Angular will not know what to inject, whereas with this:

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

the minified code might end up like this:

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

This would still work because Angular still knows what to inject. See the note on minification in the Angular tutorial.

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

like image 102
iConnor Avatar answered Nov 04 '22 06:11

iConnor