Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')       .then(function(response) {         $scope.commits = response.data       })   } 

you should use

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

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) ?

like image 804
Whisher Avatar asked Sep 13 '13 09:09

Whisher


2 Answers

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.

like image 177
Selvam Palanimalai Avatar answered Sep 21 '22 05:09

Selvam Palanimalai


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.

like image 22
OZ_ Avatar answered Sep 21 '22 05:09

OZ_