AngularJS依赖注入格式

时间:2014-02-18 09:03:32

标签: angularjs

我是棱角分明的新手,我不明白为什么$scope$http放在function这些方式之前

app.controller('PlayerController', ['$scope', '$http', 
  function($scope, $http) {
  var audio = document.createElement('audio');
  $scope.audio = audio;
  // ...

为什么这样? 阅读:http://www.ng-newsletter.com/posts/beginner2expert-services.html

2 个答案:

答案 0 :(得分:2)

放置它们是为了在缩小代码时不会破坏代码。你可以做到

function($scope, $http) {
// use $scope
}

并且Angular将从参数名称知道它需要为您提供$scope$http服务。但是当你缩小代码时,它可能变成这样的东西

function(a, b) {
// use a
}

其中a为$scope,b为$http服务。因此,AngularJS允许您指定需要注入的服务的字符串名称。 JavaScript缩小不会修改字符串,所以

['$scope', '$http', function($scope, $http) {
}]

会变成

['$scope', '$http', function(a, b) {
  // a is $scope
  // b is $http
}]

您应该阅读有关AngularJS dependency injection on Angular developer guide的更多信息。有更多的注射方法。以下是等同的:

// 1st way
app.controller('PlayerController', ['$scope', '$http', function ($scope, $http) {
}]);

// 2nd way
app.controller('PlayerController', function ($scope, $http) {
  // this will work if you don't minify your JavaScript
}]);

// 3rd way
function playerController($scope, $http) {
}
playerController['$inject'] = ['$scope', '$http'];
app.controller('PlayerController', playerController);

这不是控制器特有的。同样的事情(依赖注入风格)适用于服务,工厂等。

答案 1 :(得分:0)

据我所知,这只是为了缩小/丑化代码。如果参数被更改,则应用程序将失败。就这些;没什么特别的。

实际上,如果你没有缩小/丑化你的代码并省略有问题的字符串,它将正常工作。

相关问题