Search code examples
cssangularjscss-animationsng-animate

Simple forward and backward CSS animation with Angular ngAnimateSwap directive


I have made a simple swap animation with ng-animate-swap directive, nothing fancy. It works well in forward direction, but fails animating backwards correctly.

The problem is, that the entering slide will not be visible before animation ends.
Check an example in Plunker.

Here is the controller code:

var elem = document.querySelector('.wrap');
var $elem = angular.element(elem);

var slides = [
  { color: "#f00" },
  { color: "#0f0" },
  { color: "#00f" },
];

var current = 0;
$scope.slide = slides[ current ];

// switch to next slide
$scope.nextSlide = function(){
  $elem.removeClass('animate-back');
  if(slides.length <= ++current){
    current = 0;
  }
  $scope.slide = slides[ current ];
};

// switch to prev slide
$scope.prevSlide = function(){
  $elem.addClass('animate-back');
  if(--current<0){
    current = slides.length-1;
  }
  $scope.slide = slides[ current ];
};

the HTML:

  <div class="wrap" ng-controller="AppCtrl">
    <div class="container">
      <div ng-animate-swap="slide" class="slide" ng-style="{background:slide.color}"></div>
    </div>
    <button ng-click="prevSlide()">Previous Slide</button>
    <button ng-click="nextSlide()">Next Slide</button>
  </div>

the CSS:

.slide.ng-enter-active,
.slide.ng-leave {
  transform: translate(0,0);
}

// forward
.slide.ng-enter {
  transform: translate(0,-100%);
}
.slide.ng-leave-active {
  transform: translate(0,100%);
}

// backward
.animate-back .slide.ng-enter {
  transform: translate(0,100%);
}
.animate-back .slide.ng-leave-active {
  transform: translate(0,-100%);
}

I think it's simple CSS issue, but can not wrap my head around it.
What am I missing here?


Solution

  • You're right! The problem was the css. The direction was missing for the incoming slide. ".animate-back .slide.ng-enter-active" This should work.

    .animate-back .slide.ng-enter {
      transform: translate(0,100%);
    }
    .animate-back .slide.ng-enter-active {
    transform: translate(0,0);
    }
    .animate-back .slide.ng-leave-active {
    transform: translate(0,-100%);
    }
    

    Updated Plunker: http://plnkr.co/edit/Uze8e8DmmjlaSqEeBELe?p=preview