krs8888
krs8888

Reputation: 1349

How to correctly minify angularJS file

I have a simple angularjs directive and when I minify the file i get error because the variable names are changed

var app= angular.module('app',[]);

app.directive('directive',function(){
    return {
        restrict: 'EA',
        scope: {},
        replace: true,
        link: function($scope, element, attributes){
            $scope.name="test-test";
        ,
        controller: function($scope,$attrs,$http){

        },
        templateUrl: 'directives/app/app.tpl.html'
    }
});

the problem is $scope.name changes into a.name and angular doesn't recognize it. I tried injecting $scope by trying something like

link: ['$scope',function($scope, element, attributes){
            $scope.name="test-test";
}],
controller: ['$scope','$attrs','$http',function($scope,$attrs,$http){

}],

but I still get the same error of a.name when minified.

Upvotes: 0

Views: 1931

Answers (2)

Bartosz Gościński
Bartosz Gościński

Reputation: 1580

Directives link functions aren't injected. They're passed fixed set of parameters which are listed and comprehensively described in angular.js documentation. However this is not the case with controller. These are injected and should be annotated before minification. You can do it in at least 3 ways:

  • using array syntax like in your example
  • setting $inject property on controller function with value being array of names of injectables
  • annotating with ngAnnotate which will detect uses of angular injection and annotate it properly

Upvotes: 2

Tamas Hegedus
Tamas Hegedus

Reputation: 29946

The link function is not dependency injected. It uses only positional arguments so you don't have to use that explicit array naming. The controller one is fine I think.

At last, remember, you must write code for clarity. The explicit syntax is a bit too verbose, that's why most people choose to use ng-annotate instead. Ng-annotate is a compilation step which will convert the code to the explicit form before minification.

Upvotes: 0

Related Questions