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

查看:27
本文介绍了Angular 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 的回答,但为了完整性,它甚至可以通过将逻辑保留在视图中而进一步简化,而不会污染"控制器:

+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>

plunker

可以通过一次性绑定进一步改进(和简化)上述版本,以减少 once 上不必要的 $watch - 这仅适用于 Angular1.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.

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

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