urish urish - 5 months ago 347
AngularJS Question

Fade effect for tabs in ui-bootstrap (Angular.JS)

How can I add fade animation to a tabset using angular-ui-bootstrap?

For example, given the following code:

<tabset>
<tab heading="Tab1">Some content</tab>
<tab heading="Tab2">Other content</tab>
</tabset>


I would like the content of the tabs to fade when switching between them. I tried to add the
fade
class to the
tab
tags (similar to how you would do it with the bootstrap3 js file), but it didn't work.

Many thanks!

Answer

Since tabset use ng-class to control "active" tab, which allow us to define fade effect with angular animation by setting opacity=0 when "active" class is removed/attached.

First, you need to load ngAnimate module by including angular-animate.js and set up dependency.

Add to your <head>:

<script src="https://code.angularjs.org/1.2.24/angular-animate.js"></script>

Set module dependency:

angular.module("myApp", ["ui.bootstrap", "ngAnimate"]);

Now add animation class to your tabset.

<tabset class="tab-animation">
    <tab heading="Tab1">Some content</tab>
    <tab heading="Tab2">Other content</tab>
</tabset>

Put following code into your css file:

/* set reference point */
.tab-animation > .tab-content {
    position: relative;
}

/* set animate effect */
.tab-animation > .tab-content > .tab-pane{
    transition: 0.2s linear opacity;
}

/* overwrite display: none and remove from document flow */
.tab-animation > .tab-content > .tab-pane.active-remove {
    position: absolute;
    top: 0;
    width: 100%;
    display: block;
}

/* opacity=0 when removing "active" class */
.tab-animation > .tab-content > .tab-pane.active-remove-active {
    opacity: 0;
}

/* opacity=0 when adding "active" class */
.tab-animation > .tab-content > .tab-pane.active-add {
    opacity: 0;
}

That's all. You can check the demo on Plunker.

Also take a look at ngAnimate doc.