What is the difference of adding (or not) an array in the parameter definition of a controller in AngularJS?


To pass data from the controller to the view in AngularJS we use the following:

Angular Scope

var x = angular.module("myApp",[]);
x.controller('myController',function($scope) {
    $scope.var1 = "valor1";
    $scope.varN = "valorN";

Receiving only the values ​​contained within the $scope .

In the official AngularJS documentation (attached at the end) referring to the $window service (JavaScript global object), they use the following configuration:

Angular + Javascript(Window) scope

var myApp = angular.module('myApp', []);
x.controller('myController', ['$scope', '$window', function($scope, $window) {
      $scope.var1 = "var1";
      $scope.varN = "varN";
      $scope.var1JS = $window.var1JS;
      $scope.var2JS = $window.var2JS;

Receiving values ​​from the $scope and $window .

For what reason do they use an array with the two scopes ( $scope , $window ) in addition to the default function in the controller parameters, if it is possible that it works only by passing the $window parameter additionally?, in this way :

let myApp = angular.module("myApp",[]);
myApp.controller("myController",function($scope,$window) {
    $scope.var1 = "valor1";
    $scope.varN = "valorN";

Assuming from the first method that if the controller recognizes the $scope service by default, it could as well with $window .

Addendum: https://docs.angularjs.org/api/ng/service/ $window


An array is used as a parameter in the controllers so that angular can identify which services to inject when compressing/obfuscating the javascript code.

If we compress the first one, angular will not be able to identify the services specified in the function's constructor and will throw an error:

var myApp=angular.module("myApp",[]);myApp.controller("myController",function(r,a){r.var1="valor1",r.varN="valorN",r.var1Js=a.var1Js,r.var2Js=a.var2Js});

Whereas if we compress/obfuscate the following code, Angular knows which services to inject by the names of the services specified in the array:

var myApp=angular.module("myApp",[]);x.controller("myController",["$scope","$window",function(r,a){r.var1="var1",r.varN="varN",r.var1JS=a.var1JS,r.var2JS=a.var2JS}]);

parametro r = $scope
parametro b = $window

Scroll to Top