user2454455
user2454455

Reputation:

AngularJS Dependency Injection Format

I am new to angular, I dont understand why $scope and $http is placed before function these way

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

Why do it that way? Reading : http://www.ng-newsletter.com/posts/beginner2expert-services.html

Upvotes: 0

Views: 189

Answers (2)

Nikola Radosavljević
Nikola Radosavljević

Reputation: 6911

They are placed so that code doesn't get broken when you minify it. You could do just

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

and Angular will know from parameter names that it needs to give you $scope and $http service. But when you minify the code, it could become something like this

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

where a is $scope and b is $http service. For that reason, AngularJS allows you to specify as string names of services you need injected. JavaScript minification doesn't modify strings, so

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

would become

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

You should read more about AngularJS dependency injection on Angular developer guide. There are more ways to do injection. Following are equivalent:

// 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);

This is not something specific for controllers. Same thing (Dependency injection style) applies for services, factories etc.

Upvotes: 2

Cory Silva
Cory Silva

Reputation: 2811

From what I understand it is just for minification/uglifying the code. If the parameters get changed then the app will fail. That is all; nothing special.

Actually if you do not minification/uglifying your code and omit the strings in question it will work fine.

Upvotes: 0

Related Questions