Angularjs minify best practice

Angularjs minify best practice

I’m reading http://www.alexrothenberg.com/2013/02/11/the-magic-behind-angularjs-dependency-injection.html and
it turned out that angularjs dependency injection has problems if you minify your javascript
so I’m wondering if instead of
var MyController = function($scope, $http) {
$http.get(‘https://api.github.com/repos/angular/angular.js/commits’)
.success(function(commits) {
$scope.commits = commits
})
}

you should use
var MyController = [‘$scope’, ‘$http’, function($scope, $http) {
$http.get(‘https://api.github.com/repos/angular/angular.js/commits’)
.success(function(commits) {
$scope.commits = commits
})
}]

all in all I thought the second snippet was for the old version of angularjs but ….
Should I always use the inject way (the second one) ?

Solutions/Answers:

Solution 1:

Yes, always! So this way even if your minifer converts $scope to variable a and $http to variable b, their identity is still preserved in the strings.

See this page of AngularJS docs, scroll down to A Note on Minification.

UPDATE

Alternatively, you can use ng-annotate npm package in your build process to avoid this verbosity.

Solution 2:

It is safer to use the second variant but it is also possible to use the first variant safely with ngmin.

UPDATE:
Now ng-annotate becomes a new default tool to solve this issue.

Solution 3:

Just to point out that if you use

Yeoman

there is no need to do like

var MyController = ['$scope', '$http', function($scope, $http) {
  $http.get('https://api.github.com/repos/angular/angular.js/commits')
    .success(function(commits) {
      $scope.commits = commits
    })
}]

because grunt during minify take into account how to manage DI.

Solution 4:

Yes, you need to use explicit dependency injection (second variant). But since Angular 1.3.1 you can turn off implicit dependency injection, it’s really helpful to solve potential problems with renaming at once (before minification).

Turning off implicit DI, using strictDi config property:

angular.bootstrap(document, ['myApp'], {
    strictDi: true
});

Turning off implicit DI, using ng-strict-di directive:

<html ng-app="myApp" ng-strict-di>

Solution 5:

Like OZ_ said, Use ngmin to minify all angular js file, like directive.js service.js. After that you can use Closure compiler to optimize it.

ref:

How to minify angularjs scripts

Build with YO

Solution 6:

You might want to use $inject as it mentioned here:

MyController.$inject = ['$scope', '$http'];

function MyController($scope, $http) {
  $http.get('https://api.github.com/repos/angular/angular.js/commits')
    .success(function(commits) {
      $scope.commits = commits
    })
}