Angularjs 缩小了最佳实践

我在读 http://www.alexrothenberg.com/2013/02/11/the-magic-behind-angularjs-dependency-injection.html 事实证明,如果缩小 javascript,angularjs 依赖注入就会出现问题 所以我在想

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

你应该用

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
})
}]

总而言之,我认为第二个片段是为古老版本的 angularjs 准备的,但是... ..。

我应该总是使用注射方式(第二种) ?

103234 次浏览

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.

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.

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

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

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

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>

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

Use Strict Dependency Injection to Diagnose Problems

With Implicit Annotation, code will break when minified.

From the Docs:

Implicit Annotation

Careful: If you plan to minify your code, your service names will get renamed and break your app.

You can add an ng-strict-di directive on the same element as ng-app to opt into strict DI mode.

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

Strict mode throws an error whenever a service tries to use implicit annotations.

This can be useful to determining finding problems.

For more information, see