我刚开始学习AngularJS,我不知道为什么我会继续看到以下两种不同的方式。只有第一种方式适合我,如果我尝试第二种方式依赖项不起作用。有什么区别,哪个是正确的?
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');
}
});
答案 0 :(得分:2)
如果正确设置应用程序,这两个版本都应该有效。
选项1 使用strict dependency injection,这就是您传递将注入控制器的对象名称的原因。
严格的DI将允许代码缩小,您可以根据需要命名传递控制器函数的参数(参见示例)。
您必须通过传递可选对象在引导调用中声明严格的依赖注入:
angular.bootstrap(window.document, ['appModule'], {
strictDi: true
});
选项2 不使用严格的DI(默认行为):作为参数注入的名称必须反映框架使用的名称。
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>
&#13;
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']);
&#13;
<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>
&#13;