注射器对全局变量不能做什么?

时间:2013-05-30 12:51:45

标签: angularjs

所以在AngularJS docs我看到了关于注射器的事情:

// You write functions such as this one.
function doSomething(serviceA, serviceB) {
  // do something here.
}

// Angular provides the injector for your application
var $injector = ...;

///////////////////////////////////////////////
// the old-school way of getting dependencies.
var serviceA = $injector.get('serviceA');
var serviceB = $injector.get('serviceB');

// now call the function
doSomething(serviceA, serviceB);

///////////////////////////////////////////////
// the cool way of getting dependencies.
// the $injector will supply the arguments to the function automatically
$injector.invoke(doSomething); // This is how the framework calls your functions
它看起来不错。但我不明白。在注入器寻找依赖关系的最后一行,是不是就像拥有全局变量serviceA,serviceB?我的意思是,我会像这样重写它:

var serviceA, serviceB; 
function doSomething() {
   // access serviceA, serviceB
}

让注射器做到这一点有什么好处?我的意思是,如果他能够神奇地为参数找到正确的对象,那么它是否意味着如果它们是全局变量就能轻易找到它们?

我希望我的问题很明确......

1 个答案:

答案 0 :(得分:-1)

顺便说一句,如果你做的事情真的需要低于美元范围,Angular会为你提供保障:

http://docs.angularjs.org/api/ng.$rootScope

$ rootScope的文档有点轻松,但一般来说,你注入它并使用它与常规$ scope相同。它是您所在应用程序的共享根范围。

使用Window范围的唯一原因是在多个Angular应用程序之间进行通信。即便如此......你明白了,Angular让你满意:

http://docs.angularjs.org/api/ng.$window