angularjsminifycassette

Minification is breaking my AngularJs code


I'm using Cassette which uses the Microsoft Ajax Minifier to minify JS. This minifier renames variables, including variables that have special meaning to Angular, such as $scope and $http. So Cassette breaks my Angular code!

How can I prevent this happening?

For reference, this is the Angular code which is being broken. The $scope and $http function parameters are being renamed:

// <reference path="vendor/angular.js" />

angular.module('account-module', [])
    .controller('ForgottenPasswordController', function ($scope, $http) {

        $scope.email = {
            value: '',
            isValid: false,
            containerStyle: "unvalidated",
            validate: function () {
                var valid = isEmailAdressValid($scope.email.value);
                $scope.email.isValid = valid;
                $scope.email.containerStyle = valid ? "valid" : "invalid";
                return valid;
            },
            removeErrorMessage: function() {
                $scope.email.containerStyle = "unvalidated";
            }
        };

        $scope.display = {
            formClass: '',
            congratulationsClass: 'hide'
        };

        $scope.submit = function (event) {
            event.preventDefault();

            var emailValid = $scope.email.validate();
            if (emailValid) {
                $http({
                    method: 'POST',
                    url: '/account/forgot-password',
                    params: { email: $scope.email.value },
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                }).success(function(data) {
                    $scope.success(data);
                }).error(function() { $scope.error(); });
            }
        };

        $scope.success = function (data) {
            switch (data.Outcome) {
                case 1:
                    $scope.display.formClass = "hide";
                    $scope.display.congratulationsClass = "";
                    break;
                case 2:
                    $scope.email.containerStyle = "invalid";
                    break; 
            }
        };

        $scope.error = function () {
            alert('Sorry, an error occurred.');
        };

        function isEmailAdressValid(emailAddress) {
            return /[^\s@]+@[^\s@]+\.[^\s@]+/.test(emailAddress);
        }
    });

Solution

  • To prevent code minifiers from destroying your angular application, you have to use the array syntax to define controllers.

    Look at http://odetocode.com/blogs/scott/archive/2013/03/13/angularjs-controllers-dependencies-and-minification.aspx

    (From OP): For reference, here is the changed code:

    angular.module('account-module', [])
        .controller('ForgottenPasswordController', ["$scope", "$http", function ($scope, $http) {
    ...
    }]);