Search code examples
javascriptangularjscss-animationsng-hide

How to fade out element using ng-hide with AngularJS?


I can currently show/hide an element according to a boolean condition in my controller. How can I fade the element out if the condition is true instead of just instantly hiding it?

<div id='conversion-image' ng-hide="pages.length > 0">
    generating pages...
    <br />
    <img src='Images/ajax-loader-blue.gif' />
</div>

I also already have the ngAnimate dependancy included as well.

var app = angular.module("app", ["ngAnimate"]);

Solution

  • You can do it with CSS and ng-animate as the following:

    .fade-out.ng-hide {
      opacity: 0;
    }
    
    .fade-out.ng-hide-add, .fade-out.ng-hide-remove {
      transition: all linear 0.5s;
    }
    
    .check-element {
      border: 1px solid black;
      opacity: 1;
      padding: 10px;
    }
    <head>
      <meta charset="UTF-8">
      <link href="animations.css" rel="stylesheet" type="text/css">
      <script src="//code.angularjs.org/snapshot/angular.min.js"></script>
      <script src="//code.angularjs.org/snapshot/angular-animate.js"></script>      
    </head>
    
    <body ng-app="ngAnimate">
      Hide: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br />
      <div class="check-element fade-out" ng-hide="checked">
        I fade out when your checkbox is checked.
      </div>
    </body>

    Angular ng-hide docs