Angularjs缩小了最佳实践

Whi*_*her 100 javascript dependency-injection 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
      })
  }
Run Code Online (Sandbox Code Playgroud)

你应该使用

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
    })
}]
Run Code Online (Sandbox Code Playgroud)

总而言之,我认为第二个片段是旧版本的angularjs,但....

我应该总是使用注入方式(第二个)吗?

Sel*_*lai 100

是的,总是!所以这种方式即使你的minifer将$ scope转换为变量a和$ http转换为变量b,它们的身份仍然保留在字符串中.

请参阅AngularJS文档的此页面,向下滚动到关于缩小的A Note.

UPDATE

或者,您可以在构建过程中使用ng-annotate npm包来避免这种冗长.

  • 在运行缩小之前,您可以使用ngmin和构建工具(如Grunt),而不是使用这种更详细的语法.这样你就可以正确缩小,但也可以使用依赖注入语法. (8认同)
  • 关于缩小的说明已移至https://docs.angularjs.org/tutorial/step_07 (4认同)

OZ_*_*OZ_ 36

使用第二种变体更安全,但也可以使用ngmin安全地使用第一种变体.

更新:
现在ng-annotate成为解决此问题的新默认工具.


Whi*_*her 6

只是要指出,如果你使用

约曼

没有必要这样做

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
    })
}]
Run Code Online (Sandbox Code Playgroud)

因为minify期间的grunt考虑了如何管理DI.


diz*_*l3d 6

是的,您需要使用显式依赖注入(第二个变体).但是从Angular 1.3.1开始,你可以关闭隐式依赖注入,这对于解决立即重命名(缩小之前)的潜在问题非常有帮助.

使用strictDiconfig属性关闭隐式DI :

angular.bootstrap(document, ['myApp'], {
    strictDi: true
});
Run Code Online (Sandbox Code Playgroud)

关闭隐式DI,使用ng-strict-di指令:

<html ng-app="myApp" ng-strict-di>
Run Code Online (Sandbox Code Playgroud)