且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么时候支持 ng-if 和 ng-show/ng-hide?

更新时间:2022-02-18 04:02:47

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

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?