AngularJs - 指令.compile不实例化ng-controller

时间:2013-04-29 20:48:47

标签: angularjs

以下是plunker:

http://plnkr.co/edit/4SakSg6x5wuQQ5eYBwFN?p=preview

正如您所看到的,我有两个自定义指令:child-one和child-two。这两个指令在所有方面都是相同的,除了:

 1. child-one is within an html element that has the attribute ng-controller; and,
 2. child-two is not within such an html element, rather it's ng-controller is acquired thru the
    directive's .compile method, retrieving the controller thru the attribute var-ctrl.

Child-one确实填充了这些项目,而child-two没有填充。

问题:

如果我不想让ng-controller超出指令,我必须对2岁儿童做些什么呢?

1 个答案:

答案 0 :(得分:0)

我认为该指令将自己的控制器附加到模板的根元素(即<div id="ctlrId">),但您也尝试使用ng-controller将另一个控制器附加到该元素。我认为这不会起作用。如果您将模板包装在<div>...</div>中,则会创建HomeCtrl:plunker。在plunker中,我向HomeCtrl添加了alert()以显示它现在被调用了两次。

但是现在你有一个不同的问题:与HomeCtrl相关联的$ scope现在是隔离范围的子范围。因此,您在child-two中的child2.html元素上定义的所有属性都将是未定义的。您无法在指令的模板中定义控制器,同时尝试将该控制器范围内的属性传递给指令。

相关问题