ngIf 和 ngSwitch AngularJS [英] ngIf and ngSwitch AngularJS

查看:37
本文介绍了ngIf 和 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?

是否存在 ngSwitchngIf 不是直接替换的情况?或者他们唯一的实际区别是语法?

Is there a situation where ngSwitch and ngIf are not direct replacements? Or is their only practical difference the syntax?

推荐答案

Michele Tilley 完全正确,我相信,特别是指出与 ngShow/ngHide 的对比.还有一个需要注意的区别:ng-If 将分离并重新附加一个元素就地.但是 ng-Switch 有一个外部包含元素,您可以在该元素上声明主要指令及其条件:ng-switch="expression".该外部元素中的条件内容将被 append()-ed 作为外部元素的最后一个子元素,从而改变其相对于该外部元素中的任何非条件内容的位置外部元素.

Michele 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.

并且,请参阅 this CodePen 以查看所有三个的交互式演示,显示执行上的差异.

And, see this CodePen for an interactive demo of all three, showing the differences in execution.

此行为在 Angular 1.2 中发生了变化.元素现在留在原地.上面的 Codepen 提到并演示了这一点,提供了一个指向 1.08 Plunk 的链接,该版本可悲地被消灭了......

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆