Mastering Web Application

(Rick Simeone) #1
Chapter 12
var ctrlFn = function($scope, $location) {};
console.log(ctrlFn.toString());

This technique upon execution, will log the body of the function method as a string:


"function ($scope, $location) {}"

With the declaration of the function method captured as a string, it is enough to
do some simple regular expression matching to parse out the names of declared
arguments, and thus find out names of required dependencies.


Now, let's consider what happens with function definitions during the JavaScript
minification process. The exact details will vary from one processor to another but
most minifiers will rename function arguments so the code will look similar to the
following code:


angular.module('projects', ['resources.projects'])
.controller('ProjectsViewCtrl', function (e, f) {
//minified controller's code referencing new argument names
});

Obviously AngularJS can't discover dependencies from minified functions, as e and
f are not valid service names.


Writing minification-safe JavaScript code

Standard JavaScript minification processes the destroy parameter information that
is needed by AngularJS to infer dependencies. Since this information is lost from the
signature of function, we need to provide hints using different constructs.


AngularJS offers different ways of providing dependency hints for the minified code,
but we would like to encourage you to use array-style annotations as shown in the
following example:


angular.module('projects', ['resources.projects'])
.controller('ProjectsViewCtrl', ['$scope', '$location', function
($scope, $location) {
//controller's code
}]);

This code when minified, would look as follows:


angular.module('projects', ['resources.projects'])
.controller('ProjectsViewCtrl', ['$scope', '$location', function (e,
f) {
//controller's code
}]);
Free download pdf