角ng-if和ng-show组合 [英] Angular ng-if and ng-show combination

查看:65
本文介绍了角ng-if和ng-show组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下可能会在网页上呈现的大量内容,例如图表. Angular提供2个选项来切换内容的可见性.

Imagine some heavy content that might be rendered on a web page, such as a chart. Angular gives 2 options to toggle the visibility of said content.

ng-show 将呈现内容而不管其内容如何,​​并在事实发生后简单地隐藏".这是不理想的,因为用户在会话期间可能永远不会打开"内容,因此呈现它是浪费的.

ng-show will render the content regardless of the expression and simple "hide" it after the fact. This is not ideal since the user may never "open" the content during their session, so it was a waste to render it.

ng-if 更好.如果表达式为假,则用它代替ng-show可以防止首先显示大量内容.但是,它的优点也是缺点,因为如果用户隐藏该图表然后再次显示它,则每次都会从头开始呈现内容.

ng-if is better in this regard. Using it in place of ng-show will prevent the heavy content from being rendered in the first place if the expression is false. However, its strength is also its weakness, because if the user hides the chart and then shows it again, the content is rendered from scratch each time.

我该如何制定一个兼顾两全其美的指令?这意味着它就像ng-if一样工作,直到第一次渲染内容为止,然后切换为像ng-show一样工作,以防止每次都重新渲染它.

How can I make a directive that takes the best of both worlds? Meaning it works like ng-if until the content is rendered the first time, then switches to work like ng-show to prevent re-rendering it each time.

推荐答案

+1关于Denis的答案,但仅出于完整性考虑,甚至可以通过将逻辑保留在View中而不污染"控制器来进一步简化它:

+1 on Denis's answer, but just for completeness-sake, it can even be simplified further by keeping the logic in the View without "polluting" the controller:

<button ng-click="show = !show">toggle</button>
<div ng-if="once = once || show" ng-show="show">Heavy content</div>

朋克车

可以通过一次性绑定来进一步改进(简化)上述版本,以减少once上不必要的$ watch-仅在Angular 1.3+中有效:

the version above could be further improved (and simplified) with one-time binding to reduce an unnecessary $watch on once - this will only work in Angular 1.3+:

<div ng-if="::show || undefined" ng-show="show">Heavy content</div>

需要undefined来确保监视的值不稳定" "变成true.一旦稳定下来,它也会失去$ watch,因此不会受到show的任何进一步更改的影响.

The undefined is needed to ensure that the watched value does not "stabilize" before it becomes true. Once it stabilizes, it also loses the $watch, so it would not be impacted by any further change to show.

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

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