1

Here I have a $scope.content with a paragraph of text. When a user clicks the next button, I replace the $scope.content text.

This text transition isn't very smooth, so I would like to add a simple transition fade in the following order:

  1. User click the next button
  2. The current $scope.content div will fade out
  3. After the fade out animation has completed, replace the $scope.content
  4. Then instantly show the new text (no animation)

angular
  .module('app', [])
  .controller('Controller', function ($scope) {    
    var data = [
      'Here is slide #1',
      'Another slide, it is #2',
      'Can I get another? Yep! #3',
      'Last but not least, slide #4'
    ];

    $scope.slide = 0;
    $scope.content = data[$scope.slide];
    
    
    $scope.next = function () {
      $scope.slide++;
      $scope.content = data[$scope.slide];
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="Controller">

<div>{{content}}</div>

<button ng-click="next()">Next</button>

</div>
georgeawg
  • 48,608
  • 13
  • 72
  • 95
floatleft
  • 6,243
  • 12
  • 43
  • 53

1 Answers1

0

To achieve expected result , use ngClass and $timeout with CSS transition

  1. Add ngClass for fadeIn and fadeOut
  2. On every click for next , add fadeOutclass and after timeout of 2s, add content and fadeIn

angular
  .module('app', [])
  .controller('Controller', function ($scope, $timeout) {    
    var data = [
      'Here is slide #1',
      'Another slide, it is #2',
      'Can I get another? Yep! #3',
      'Last but not least, slide #4'
    ];

    $scope.slide = 0;
    $scope.content = data[$scope.slide]
    
    
    $scope.next = function () {
       $scope.slide++;
       $scope.fadeCheck = true;
       $timeout(function(){
         $scope.content = data[$scope.slide];
         $scope.fadeCheck = false;
       },2000)
    };
  });
.fadeIn {
  visibility: visible;
  opacity: 1;
  transition: opacity 2s linear;
}

.fadeOut{
   visibility: hidden;
  opacity: 0;
  transition: visibility 0s 2s, opacity 2s linear;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="Controller">

<div ng-class="{fadeOut:fadeCheck==true,fadeIn:fadeCheck==true}" >{{content}}</div>

<button ng-click="next()">Next</button>

</div>

Code sample - https://codepen.io/nagasai/pen/aYmvQg

Naga Sai A
  • 10,771
  • 1
  • 21
  • 40