Search code examples
angularjsng-animate

Can't seem to animate ng-show AngularJS


I am trying to do a fade in animation when ng-show condition is met. I can see the animation for ng-hide but not for ng-show.

HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.9/angular.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/angular-animate.js"></script>
<div data-ng-app="myApp" data-ng-controller="myCtrl">
  <input type="text" data-ng-model="name"/>
  <input type="button" data-ng-click="click()" value="Click"/>
  <input type="button" data-ng-click="reset()" value="Reset"/>
  <div data-ng-show="bool" class="test">
     {{name}}
  </div>
</div>

CSS

.test.ng-show{
  transition:1s linear all;
  opacity:0;
}
.test.ng-show.ng-show-active{
   opacity:1;
}

JS

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

app.controller('myCtrl',function($scope){
    $scope.name='';
  $scope.bool=false;
  $scope.click=function(){
    $scope.bool=true;
  };
  $scope.reset=function(){
    $scope.bool=false;
    $scope.name='';
  };
});

Here's a link to the JSFiddle of my code.


Solution

  • You can update the CSS to achieve this. Click on Toggle button to see the better animation toggle effect.

    var app = angular.module('myApp', ['ngAnimate']);
    app.controller('myCtrl', function($scope) {
      $scope.name = 'Hello World!';
      $scope.bool = false;
      $scope.click = function() {
        $scope.bool = true;
      };
      $scope.reset = function() {
        $scope.bool = false;
        $scope.name = '';
      };
    });
    .test.ng-hide-add,
    .test.ng-hide-remove {
      transition: 1s linear all;
      opacity: 1;
    }
    .test.ng-hide {
      opacity: 0;
    }
    .test{ margin-top:20px;font-size:2rem}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.9/angular.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/angular-animate.js"></script>
    <div data-ng-app="myApp" data-ng-controller="myCtrl">
      <input type="text" data-ng-model="name" />
      <input type="button" data-ng-click="click()" value="Click" />
      <input type="button" data-ng-click="bool = !bool" value="Toggle" />
      <input type="button" data-ng-click="reset()" value="Reset" />
      <div data-ng-show="bool" class="test">
        {{name}}
      </div>
    </div>