2014-01-30 52 views
1

文件angular.dart/lib/directive/module.dart on GitHub 是什么值(类型,NULL)有一个像

// class NgDirectiveModule extends Module { 
// NgDirectiveModule() { 

    value(NgADirective, null); // <-- 

很多线路什么是这句话的目的。
第二个参数记录为The [value] is what actually will be injected. 为什么我要null被注入?

回答

1

你想要一个null,因为该指令不存在于根注入器中。如果没有这些陈述,尝试注入不存在的指令会导致程序崩溃,出现“未知类型”注入器错误。

随着Angular走DOM创建指令,它们可以在DOM漫游期间创建的子注入器中使用。例如

<div ng-model="foo" my-directive>...</div> 

在MyDirective指令,你可以注入任何其他指令:

class MyDirective { 
    MyDirective(NgModel model) { 
    if (model.viewValue == "party") dance(); 
    } 
} 

可以为任何指令,例如做ng-click,ng-class,但是大多数指令没有有用的公共接口。但是,null值是有用的:

class MyDirective { 
    MyDirective(NgRepeatDirective repeat) { 
    if (repeat != null) { 
     // this element is being repeated 
    } else { 
     // this element is not being repeated. 
    } 
    } 
} 
+0

非常感谢,我想我还有很多事情要了解DI如何在Angular中工作。 –

+0

我们也一样! Vojta有一些令人敬畏的工作:http://www.youtube.com/watch?v=_OGGsf1ZXMs –