javascriptangularjsfadeng-show

Angular ng-show with fade expression does not remove the div


I am trying to display a div with an error message with ng-show along with ng-class set as fade with an expression. The message fades away after the set time, however, the div created to display the error message does not get removed.

I would like the created div to be removed as well when the message fades. Could someone please help?

Here is my codepen - link

Here is my code for the html

  <link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet" 
type="text/css" />    
    <section data-ng-app="app" class="container" data-ng-controller="messageController">    

        <hr />      

      <div data-ng-show="showError" ng-class="{fade:doFade}" class="alert alert-danger"><strong>Error:</strong> {{errorMessage}}</div>

      <button data-ng-click="fakeError()" class="btn btn-default">Fake an Error</button>
      <hr />      
    </section>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>

and the JS code

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

app.controller('messageController', ['$scope', '$timeout', function($scope, $timeout){

  $scope.showError = false;
  $scope.doFade = false;

  $scope.fakeError = function(){

    //reset
    $scope.showError = false;
    $scope.doFade = false;

    $scope.showError = true;

    $scope.errorMessage = 'We\'re mixing apples and oranges!';

    $timeout(function(){
      $scope.doFade = true;
    }, 2500);
  };
}]);

Solution

  • ng-show sets only style display conditionaly, soyour div will be always present in the page, only not visible if condition is falsy.

    Use ng-if instead to conditionaly add/remove element.

    Easiest way to animate ng-if is to use angular-animate library. Using this lib you will get control over rendering stages of various directives. These stages are marked via specific css classes, which you can target and style transitions of element.

    For ng-if directive, there are available classes .ng-enter, .ng-leave, .ng-enter-active, .ng-leave-active

    Via these classes you can define desired transition, in your case it is fade.

    Example of fading on remove: https://codepen.io/anon/pen/NzyqvL