1

所以在AngularJS 文档中,我看到了关于注入器的内容:

// 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
}

让注射器这样做有什么好处?我的意思是,如果他可以神奇地为参数找到正确的对象,这是否意味着如果它们是全局变量,我可以很容易地找到它们?

我希望我的问题很清楚...

4

1 回答 1

-1

顺便说一句,如果你正在做一些真正需要低于 $scope 的事情,Angular 已经涵盖了:

http://docs.angularjs.org/api/ng.$ro​​otScope

$rootScope 的文档有点简单,但一般来说,你注入它并像普通的 $scope 一样使用它。它是您所在应用程序的共享根范围。

使用 Window 范围的唯一原因是在多个 Angular 应用程序之间进行通信。即便如此……你明白了,Angular 已经涵盖了:

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

于 2013-05-30T15:21:51.080 回答