Saqib Ali Saqib Ali - 26 days ago 12
AngularJS Question

How to fade in/out text in AngularJS app?

I have an AngularJS web application that flashes 3 words on the screen with 5 seconds on screen for each of them:

Hello
,
World
&
Goodbye
.

Here is my controller:

self.currentIndex = 0;
self.myTexts = ['Hello', 'World', 'Goodbye'];
self.currentText = self.myTexts[self.currentIndex];

var currentInterval = $interval(function() {
self.currentText = self.myTexts[++self.currentIndex % self.myTexts.length];
}, 5000);

// Clear the interval to prevent memory leaks
$scope.$on('destroy', function() {
$interval.cancel(currentInterval);
currentInterval = undefined;
});


Here is the Angular Template:

<div ng-controller="MyCtrl as myCtrl">
{{myCtrl.currentText}}
</div>


It works.

But now I want the text to fade in over the first of the five seconds and I want the text to fade out over the last of the five seconds. What is the best way to achieve that?

Answer
  1. You could do fadeIn/fadeOut with jQuery. You would need access to the element, so it would be simpler doing it in the linking function a directive where you have access to the element and the $scope. Because these events would start and finish outside of Angular's digest loop, you would need to run $scope.$apply to change the text.

  2. You could change the opacity that you could manage within the controller. Example

  3. You can create two CSS animations one for fading in, one for fading out and go through these steps:

    1. container is hidden initially
    2. select the next text
    3. apply fade-in CSS animation
    4. wait with $timeout for the same (or a bit longer) period
    5. apply fade-out CSS animation
    6. wait with $timeout for the same (or a bit longer) period
    7. repeat from step 2

The problem with the last solution is that the animation and the text changing is handled by two different timers, one by Angular's $timeout (text changing) and one by the browser's renderer (CSS animations).