Don't ng-show element until ng-hide CSS transition is complete?

ReactingToAngularVues提出了一个问题:Don't ng-show element until ng-hide CSS transition is complete?,或许与您遇到的问题类似。

回答者Abhilash P A- Pullelil给出了该问题的处理方式:

Why do you use a separate <h1> for each heading. You can use a single <h1> tag to show your heading.

I have created a demo for your problem and I have successfully done your requirement.

Updated

Note, codes are edited to use ngAnimate module. When you use ngAnimate module, it will create a class .ng-hide when you hide an element,

Here is the controller for your app,

app2.controller("testController", ["$scope", "$timeout", function ($scope, $timeout) {

    $scope.heading = {};
    $scope.heading.show = true;

    $scope.parent = {};
    $scope.parent.children = ["A", "B", "C", "D"];
    $scope.parent.activeChild = "A";

    $scope.changeHeading = function (child) {
        $timeout(function () {
            $scope.parent.activeChild = child;
            $scope.heading.show = true;
        }, 1000);

    }
}]);

And your html page should be look like this,

<div ng-controller="testController">
    <h1 class="myAnimateClass" ng-show="heading.show" ng-class="{fadeIn : heading.fadeInModel==true, fadeOut : heading.fadeOutModel}"> {{parent.activeChild}} </h1>
    <p ng-repeat="child in parent.children" ng-click="heading.show = false;changeHeading(child)">{{child}}</p>
</div>

And I have used CSS3 to implement the fade in and fade out animation,

.myAnimateClass {
    -webkit-transition: opacity 1s ease-in-out;
    -moz-transition: opacity 1s ease-in-out;
    -o-transition: opacity 1s ease-in-out;
    -ms-transition: opacity 1s ease-in-out;
    transition: opacity 1s ease-in-out;
    opacity:1;
}

.myAnimateClass.ng-hide {
    opacity: 0;
}

Explanation

To achieve your requirement, I have used ng-class and $timeout in angularJS.

You can see that, I have only one <h1> tag to display your heading. When I change the heading I just change it's binding property $scope.parent.activeChild.

And I have used two scope variables $scope.heading.fadeOutModel and $scope.heading.fadeInModel to add and remove classes fadeIn and fadeOut dynamically.

When user clicks to change the heading, I have added the class fadeOut to your heading. So, this will show an animation of fade out. And also I have fired a function in app.js, changeHeading().

You can see that, I forced the angular to wait for 1000 milliseconds to finish fade out animation. After this time, it will replace the selected heading to new one and add a class fadeIn. So, it will start animation for fade in.

Hope this will help you !!!

希望本文对你有帮助,欢迎支持JavaScript中文网