Adding css class to $ routeChangeStart doesn't trigger animation (unless in setTimeout)
I am new to Angular, so if I do any of these steps everything is wrong, please set me straight.
I am trying to get the clips on the left and right of my site to spice up the loading of the start page. Here it is in production: https://www.robotsidekick.com
As you can see it is currently working (yay). However, I am not happy with the hack I am using. Here's the relevant code:
In my controller I am listening $routeChangeStart
, and if this is the first time I call:
setTimeout(function() {
angular.element(document.querySelector('.robotarmleft')).addClass('animate-in');
angular.element(document.querySelector('.robotarmright')).addClass('animate-in');
}, 0);
This grabs two clamps, adds a class animate-in
that has the following CSS properties:
.robotarm {
margin-left: -2048px;
margin-right: -2048px;
}
.animate-in {
-webkit-transition: all 2s ease;
-moz-transition: all 2s ease;
-o-transition: all 2s ease;
transition: all 2s ease;
margin-left: -1300px;
margin-right: -1300px;
}
So the hands are (hopefully) off the screen and they bring it to life.
If, however, I add a class to the robot's arms, it's not that the setTimeout
animation doesn't start at all.
Why addClass
should this one work in setTimeout
? Should I run animation in some other type onPageLoadTheFirstTime
even for Angular? Basically looking for a suitable way to do things like this is not so good that this other hack works great.
Thanks for the help!
First, think about what you should be using $timeout
to stay in the angular vs digest loop setTimeout()
.
The timeout is probably necessary because it is executed before the DOM has rendered, which means your calls are angular.element(..)
returning []
. You will need to listen for the event that is called after the DOM is executed. Something like a ui-router $viewContentLoaded
event .
Also, using a $timeout
digest loop to delay the code is a very common solution to many problems, example .