我可以将 ng-if 指令放在也绑定到控制器的元素上吗 [英] Can I put ng-if directive on an element which also binds to a controller
问题描述
我想知道如果我在与 in 相同的元素上有一个控制器和 ng-if 指令
I was wondering in case I have a controller and ng-if directive on the same element as in
<div foo ng-if="ctrl.visible">You can see me</div>
还有一个控制器,比如
NgController(selector: ‘[foo]’,….)
class FooController { var visible = true; }
我是否应该看到你可以看到我"的文字?
Should I see the text "You can see me" or not?
推荐答案
这就是答案.我不会看到文字.基本上,ng-if
是一个嵌入指令,这意味着整个元素都被从 DOM 中剥离出来,并且在 ng-if 实例化 Block 之前不会实例化其他指令,但这永远不会发生,因为 ctrl.visible
甚至从未在示波器上发布过,所以它总是假的……鸡和蛋的问题.实际上,情况可能更糟:ctrl
可能是父控制器,如果该控制器碰巧具有可见字段,则可能会导致不可预测的行为.
Here's the answer. I would not see the text. Basically, ng-if
is a transcluding directive which means that the entire element is ripped out of the DOM and no other directives are instantiated until ng-if instantiates the Block, but that never happens because ctrl.visible
is never even published on the scope, so it's always falsy... chicken and egg problem. Actually, it can be even worse: ctrl
could be the parent controller, and if that controller happen to have visible field it can cause unpredictable behavior.
这篇关于我可以将 ng-if 指令放在也绑定到控制器的元素上吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!