BT101
BT101

Reputation: 3836

How to protect angularJS controller from minify

So I know that I need to use [] to secure my code before minification. For example:

app.controller('mainController', ['$scope', function($scope) {
    $scope.message = 'HOORAY!'; 
}]);

But how to do that when I am not using app as global variable, I've got

(function () {
'use strict';

angular
    .module('app')
    .controller('loginCtrl', Controller);

function Controller($scope, authService) {
    var vm = $scope;
    vm.login = function(login_field, password_field) {
        var loginData = {
            login: login_field,
            password: password_field
        };
        authService.login(loginData);
    };
}
})();

How to prevent it from problems during minification?

Upvotes: 0

Views: 409

Answers (4)

Moh K
Moh K

Reputation: 514

One way you may try grunt-ngmin before the minification that will searches and replace the minification with minify-friendly code. Go to this link you will see example https://github.com/btford/grunt-ngmin#example

Upvotes: 0

Estus Flask
Estus Flask

Reputation: 222493

When a controller or a service is a named function like in code above, it looks best when it's annotated with $inject (see John Papa style guide).

angular
    .module('app')
    .controller('loginCtrl', Controller);

Controller.$inject = ['$scope', 'authService'];
function Controller($scope, authService) {...}

Hoisting allows to place the annotation right above injectable function.

Upvotes: 1

donnikitos
donnikitos

Reputation: 976

I believe it should be the same way:

(function () {
'use strict';

angular
.module('app')
.controller('loginCtrl', ['$scope', 'authService', function($scope, authService) {
    $scope.login = function(login_field, password_field) {
        var loginData = {
            login: login_field,
            password: password_field
        };
        authService.login(loginData);
    };
}]);
})();

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691755

The same way:

.controller('loginCtrl', ['$scope', 'authService', Controller]);

I strongly advise you to use ng-annotate, which allows using the simple syntax, and transforms it into minifiable code for you. That will make your code simpler, easier to read, and avoid a whole lot of bugs.

Upvotes: 3

Related Questions