角度依赖性,为什么有两种不同的方式? [英] Angular dependencies, why are there two different ways?

查看:86
本文介绍了角度依赖性,为什么有两种不同的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我才刚刚开始学习AngularJS,但我不确定为什么我会继续看到以下两种不同的方式.如果我尝试第二种方式,则依赖项不起作用,只有第一种方式对我有效.有什么区别,什么是正确的?

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');
    }
});

推荐答案

如果正确设置了应用程序,则这两个版本均应工作.

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

选项1 使用严格依赖注入,这就是为什么要传递将注入到控制器中的对象名称的原因.

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

严格的DI将允许代码最小化,并且您可以根据需要命名通过控制器函数传递的参数(请参见示例).

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

选项2 不使用严格的DI(默认行为):作为参数注入的名称必须反映框架使用的名称.

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

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>

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>

这篇关于角度依赖性,为什么有两种不同的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆