1

I'm just starting to learn AngularJS and i'm not sure why i keep seeing two different ways of the following. Only the first way works for me, if i try the second way the dependencies do not work. What is the difference and which is correct?

var app = angular.module('MainCtrl', []);

// Option 1
app.controller('MainController',['$scope','$cookies','$location', function($scope, $cookies, $location) {
    if (!$cookies.get('token')) {
        $location.path('/login');
    }
}]);

// Option 2
app.controller('MainController', function($scope, $cookies, $location) {
    if (!$cookies.get('token')) {
        $location.path('/login');
    }
});
TheValyreanGroup
  • 3,554
  • 2
  • 12
  • 30
  • 'includes' is not a correct term. It's annotation https://docs.angularjs.org/guide/di#dependency-annotation . It's unclear what 'the second way the modules are not included' is supposed to mean, but I guess that this means that dependencies couldn't be injected. – Estus Flask Mar 09 '18 at 00:16
  • @estus Thanks, I edited it to “dependencies” – TheValyreanGroup Mar 09 '18 at 13:38

1 Answers1

1

Both versions should work if you set-up your application correctly.

Option 1 uses strict dependency injection, which is why you pass the names of the objects that will be injected into your controller.

Strict DI will allow for code minification, and you can name the arguments you pass the controller's function whatever you want (see example).

You will have to declare strict Dependency Injection in the bootstrap call by passing an optional object:

angular.bootstrap(window.document, ['appModule'], {
    strictDi: true
});

Option 2 does not use strict DI (default behaviour): the names injected as arguments must reflect the names used by the framework.

Option 1 - Strict dependency injection

var app = angular.module('appModule', []);

// Option 1 - Strict dependency injection
app.controller('MyController', ['$scope', function(myScope) {
    this.greeting = 'Hello World!';
    myScope.test = 'A scope property';
}]);
angular.bootstrap(window.document, ['appModule'], {
  strictDi: true
}); // Bootstrap the AngularJS app with strict dependency injection
<h2>Strict dependency injection</h2>

<div ng-controller="MyController as myCtrl">
   <p>{{ myCtrl.greeting }}</p>
   <p>{{ test }}</p>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>

Option 2 - Non-strict dependency injection

var app = angular.module('appModule', []);

// Option 2 - non strict dependency injection
app.controller('MyController', function($scope) {
  this.greeting = 'Hello World!';
  $scope.test = 'A scope property';
});
angular.bootstrap(window.document, ['appModule']);
<h2>Non-strict dependency injection</h2>
<div ng-controller="MyController as myCtrl">
  <p>{{ myCtrl.greeting }}</p>
  <p>{{ test }}</p>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
Sébastien
  • 11,860
  • 11
  • 58
  • 78