如何使用 AngularJS 同时 ngShow 和 ngHide 两个不同的元素? [英] How do I ngShow and ngHide two different elements at the same time with AngularJS?

查看:18
本文介绍了如何使用 AngularJS 同时 ngShow 和 ngHide 两个不同的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有两个独占的元素:

So I have two elements that are exclusive:

<span>foo</span>
<span>bar</span>

我给它们添加了 ngShow 和 ngHide:

And I added ngShow and ngHide to them:

<span ng-show="fooTime">foo</span>
<span ng-hide="fooTime">bar</span>

但是现在当这些渲染时,它们都显示在一瞬间.

But now when these render, there is a split second where they both show.

如何让它们同时显示/隐藏?

How can I make them show/hide at the same time?

推荐答案

使用 ngSwitch 而不是 ngShow/ngHide:

<span ng-switch="fooTime">
    <span ng-switch-when="true">foo</span>
    <span ng-switch-when="false">bar</span>
</span>

为什么?

当使用单独的 ngShow/ngHides 时,每个元素都会获得一个单独的 $watch,它异步执行,从而在事件之间留下潜在的间隙.通过使用 ngSwitch,只需设置一个 $watch,因此它们必须同时渲染.

When using the separate ngShow/ngHides, each element is getting a separate $watch which execute asynchronously leaving the potential for a gap between the events. By using ngSwitch, only one $watch is setup so they must render at the same time.

我是如何使用 ngSwitch 的?

在我第一次尝试时,我意识到手表并没有捆绑在一起,所以我求助于让 CSS 将更改捆绑在一起:

On my first attempt, I realized the watches were not tied together, so I resorted to letting CSS tie the changes together:

<style>
    [first] .fooTime {
        display: inline;
    }
    [second] .fooTime, [first] {
        display: none;
    }
</style>

<span ng-class="{'fooTime':fooTime}">
    <span first>foo</span>
    <span second>bar</span>
</span>

但 ngSwitch 更干净.

But ngSwitch is much more clean.

似乎 ngSwitch 触发器进入和离开动画 所以如果你使用 ngAnimate,有一个默认值0.2 秒的过渡.我还没有找到解决这个问题的方法.

It seems ngSwitch triggers enter and leave animations so if you are using ngAnimate, there is a default of a .2 second transition. I haven't found a way around this yet.

这篇关于如何使用 AngularJS 同时 ngShow 和 ngHide 两个不同的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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