ngIf和ngSwitch AngularJS [英] ngIf and ngSwitch AngularJS
问题描述
有什么 ngIf
和 ngSwitch
?这两个指令操作DOM,但 ngSwitch
更详细。是只用典型案例 ngIf
除非你需要一些真正的大在这种情况下使用 ngSwitch
?
What's practical difference between ngIf
and ngSwitch
? Both directives manipulate the DOM, but ngSwitch
is more verbose. Is the typical case to just use ngIf
unless you need something really big in which case use ngSwitch
?
是否有一个情况 ngSwitch
和 ngIf
不是直接替代品?或者是他们的唯一区别语法?
Is there a situation where ngSwitch
and ngIf
are not direct replacements? Or is their only practical difference the syntax?
推荐答案
布兰登蒂利的得到完全理解这一点,我相信,特别是在指出与对照 ngShow
/ ngHide
。还有一个额外的区别需要注意: NG-如果
将分离并就地再附加一个元素的 的。但 NG-开关
具有包含在其声明的主要指令及其状况元素外: NG-开关=前pression
。该外部元素中的条件内容将是追加()
-ed为的最后一个子的外部元件,从而改变相对于它的任何位置外部元件内的非条件内容。
Brandon Tilley's got it exactly right, I believe, particularly in pointing out the contrast with ngShow
/ngHide
. There's one additional difference to note: ng-If
will detach and re-attach an element in-place. But ng-Switch
has an outer containing element on which you declare the main directive and its condition: ng-switch="expression"
. The conditional content within that outer element will be append()
-ed as the last child of the outer element, thus changing its position relative to any non-conditional content within the outer element.
和,请参见这个codePEN 所有三个互动演示,展示在执行中的差异。
And, see this CodePen for an interactive demo of all three, showing the differences in execution.
编辑:此行为角1.2改变。元素现在留在原地。上面的codePEN提到并演示了这一点,从而能够在1.08普拉克的链接已经黯然被打掉了......
This behavior changed in Angular 1.2. Elements are now left in place. The Codepen above mentions and demonstrates this, providing a link to a 1.08 Plunk that has sadly been wiped out...
这篇关于ngIf和ngSwitch AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!