Your Angular.js directives will break when minified. This is how you write directives #likeaboss

Surprisingly enough, if you write your directive controllers as per the documentation, they will break when minified.
Image
IMO the standard should be to write minification compatible code. The docs do talk about using the minfication-compatible square-brakets [] DI syntax for controllers and such, but not for directive controllers. In fact every directive I’ve ever seen in videos, at meetups or in docs will break when minified.
As per my testing below, square brackets are required for directive controllers too. This is how you do it:
Documented way (breaks)
var myModule = angular.module('myModule', []);
myModule.directive('breaksWhenMinified', ['anyService', function(anyService) {
  return {
    restrict: 'A',
    controller: function($scope, $attrs, $element) {
        alert($scope.whatever);
    }
});
Notice that it doesn’t matter if you use square brackets at the directive level, the minifier still destroys the parameter names of the controller function.
EDIT: Michael has noted in the comments below that anywhere AngularJS expects a function, it can also take an array. We will use the array syntax here because it can be minified. NB: even though the link function takes specially named parameters, it doesn’t require the array syntax!
Undocumented way (works)
var myModule = angular.module('myModule', []);
myModule.directive('breaksWhenMinified', ['anyService', function(anyService) {

  return {
    restrict: 'A',
    controller: ['$scope', '$attrs', '$element', function($scope, $attrs, $element) {
      alert($scope.whatever);
    }]
 };

});
I don’t understand why the docs teach you to write code that is incompatible with minification. Even in the videos, people are writing code that will break when minified. You have been warned!

4 thoughts on “Your Angular.js directives will break when minified. This is how you write directives #likeaboss

  1. Thanks! Why don’t you add this to the angular docs? I’d do it but I don’t want to steal your credit. People would definitely benefit from this.

Leave a comment