什么时候支持 ng-if 和 ng-show/ng-hide? [英] When to favor ng-if vs. ng-show/ng-hide?

查看:21
本文介绍了什么时候支持 ng-if 和 ng-show/ng-hide?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解 ng-showng-hide 会影响元素上设置的类,并且 ng-if 控制元素是否作为 DOM 的一部分呈现.

I understand that ng-show and ng-hide affect the class set on an element and that ng-if controls whether an element is rendered as part of the DOM.

是否有关于选择 ng-if 而不是 ng-show/ng-hide 的指南,反之亦然?

Are there guidelines on choosing ng-if over ng-show/ng-hide or vice-versa?

推荐答案

取决于您的用例,但总结一下区别:

Depends on your use case but to summarise the difference:

  1. ng-if 将从 DOM 中删除元素.这意味着您的所有处理程序或附加到这些元素的任何其他内容都将丢失.例如,如果您将点击处理程序绑定到子元素之一,当 ng-if 评估为 false 时,该元素将从 DOM 中删除并且您的点击处理程序将不再工作,即使在 ng-if 稍后计算为 true 并显示该元素.您将需要重新附加处理程序.
  2. ng-show/ng-hide 不会从 DOM 中删除元素.它使用 CSS 样式来隐藏/显示元素(注意:您可能需要添加自己的类).这样一来,您与孩子相关的处理程序就不会丢失.
  3. ng-if 创建一个子作用域,而 ng-show/ng-hide 不会
  1. ng-if will remove elements from DOM. This means that all your handlers or anything else attached to those elements will be lost. For example, if you bound a click handler to one of child elements, when ng-if evaluates to false, that element will be removed from DOM and your click handler will not work any more, even after ng-if later evaluates to true and displays the element. You will need to reattach the handler.
  2. ng-show/ng-hide does not remove the elements from DOM. It uses CSS styles to hide/show elements (note: you might need to add your own classes). This way your handlers that were attached to children will not be lost.
  3. ng-if creates a child scope while ng-show/ng-hide does not

ng-show/ng-hide 相比,不在 DOM 中的元素对性能的影响较小,并且在使用 ng-if 时,您的网络应用程序可能看起来更快>.根据我的经验,差异可以忽略不计.当同时使用 ng-show/ng-hideng-if 时,动画是可能的,在 Angular 文档中都有示例.

Elements that are not in the DOM have less performance impact and your web app might appear to be faster when using ng-if compared to ng-show/ng-hide. In my experience, the difference is negligible. Animations are possible when using both ng-show/ng-hide and ng-if, with examples for both in the Angular documentation.

最终,您需要回答的问题是您是否可以从 DOM 中删除元素?

Ultimately, the question you need to answer is whether you can remove element from DOM or not?

这篇关于什么时候支持 ng-if 和 ng-show/ng-hide?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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