When specific conditions are met in my controller, I apply two CSS3 animations to the DOM using ng-class. The animations (shake Y & shake X) are added based on certain criteria being satisfied. Here is a snippet of the relevant JavaScript code:
$scope.submitAnswer = function($index) {
if ($index == current) {
console.log('correct!');
$scope.shaken = 'shakeY';
}
else {
console.log('incorrect!');
$scope.shaken = 'shakeX';
}
}
Here's the corresponding HTML:
<div
id="philosopher"
ng-class="shaken"
ng-click="submitAnswer($index);"
ng-repeat="philosopher in philosophers">
<img ng-src="images/{{philosopher.signifier}}.png" height="142px" width="auto" />
<h2>{{philosopher.name}}</h2>
</div>
Although this setup works as intended, I've encountered an issue where I can't keep reapplying the same animation class consecutively - I need to switch between triggering the if statement and the else statement.
I came up with a custom directive using ngAnimate to repeatedly trigger the animation. However, I'm struggling to implement separate animations based on the outcome of the if-else statement. Here's an example of one of the directives I tried:
app.directive('shake', function($animate) {
return {
restrict: 'A',
scope: false,
link: function(scope, element, attrs) {
element.bind('click', function() {
$animate.addClass(element, 'shakeX', function() {
$animate.removeClass(element, 'shakeX');
});
});
}
};
});
How can I continuously reapply shakeX and shakeY to ng-class or only use my directive based on the result of the if-else statement?
EDIT
I was able to resolve the issue! After some trial and error, I found that implementing a timeout function within the if statement worked perfectly. Although it may not be conventional to use functions inside if statements, this approach got the desired animation effect. Here's how I achieved it:
if ($index == current) {
console.log('correct!');
$timeout(function() {
$scope.shaken = 'shakeY'
})
}
else {
console.log('incorrect!');
$timeout(function() {
$scope.shaken = 'shakeX'
})
}