了解 AngularJS 控制器中的依赖注入 [英] Understanding dependency injection in AngularJS controllers

查看:36
本文介绍了了解 AngularJS 控制器中的依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚刚学习依赖注入,我想我开始理解它了.

Just learning dependency injection, and I think I'm starting to understand it.

请告诉我我是否在正确的轨道上...

Please tell me if I'm on the right track...

例如:这两个等价吗?

/* injection method */
function <controller_name>($scope) {}
<controller_name>.$inject = ['$scope'];

/* other method */
var app = angular.module('myApp');
app.controller(<controller_name>, function($scope) {});

推荐答案

首先澄清一下:

对于依赖注入,无论您是使用全局函数还是作为 module.controller(...) 方法的参数声明控制器都没有关系.依赖注入器只关心函数本身.所以你实际上要问的是这两者的等价性:

For dependency injection, it doesn't matter whether you declare a controller using a global function or as the argument of module.controller(...) method. Dependency injector is only concerned about the function itself. So what you're actually asking about is the equivalence of those two:

// First

function MyController($scope) {}

MyController.$inject = [ '$scope '];

// Second

function($scope) {}

而且因为控制器函数是否匿名对于注入器来说也无关紧要,所以上面两个也可以:

And because whether the controller function is anonymous or not also doesn't matter for the injector, the above two can just as well be:

// First

function MyController($scope) {}

MyController.$inject = [ '$scope '];

// Second

function MyController($scope) {}

现在很明显,您的两个控制器之间的唯一区别是其中一个控制器中存在 $inject 属性.

Now it's clear that the only difference between your two controllers is the presence of the $inject property in one of them.

这是您问题的实际答案:

这两个控制器几乎相同.两者都将接收 $scope 作为参数并且功能相同.但是,如果您决定稍后缩小代码,则只有设置了 $inject 数组的版本才能正常工作.这是因为如果您不指定 $inject 数组,也不使用内联注释方法 (http://docs.angularjs.org/guide/di#inlineannotation),注入器找出您感兴趣的依赖项的唯一方法是检查您的函数参数的名称(将它们视为服务 ID).但是缩小会随机命名这些参数,从而消除以这种方式识别依赖项的机会.

These two controllers are almost the same. Both will receive the $scope as the argument and will function the same. However, if you decide to minify your code later, only the version with $inject array set on it will work properly. This is because if you don't specify the $inject array nor use the inline annotation approach (http://docs.angularjs.org/guide/di#inlineannotation), the only way for the injector to find out which dependencies you were interested in is to check the names of your function arguments (treating them as service IDs). But minification would name those arguments randomly thus removing the chance to recognize dependencies this way.

因此,如果您要缩小代码,则必须使用 $inject 数组或内联注释显式指定依赖项,否则,任何版本都可以正常工作.

So if you're going to minify your code, you have to specify the dependencies explicitly using $inject array or inline annotation, otherwise, any version will work just as good.

这篇关于了解 AngularJS 控制器中的依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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