Home Ask Login Register

Developers Planet

Your answer is one click away!

jdherder February 2016

AngularJS: CSS Animation On Click (ngClick)

I've seen several questions related to CSS animations 'on click' in Angular when researching this, but generally without any solid or definitive answers.

I want to know the best practice way to achieve a CSS animation when clicking on an element in an AngularJS environment (1.x). Specifically, lets say we want to utilize an animation from Animate.CSS and each time we click on the element in question this animation should happen.

Here is the route I have taken currently, but wonder if there might be a better way:

Markup:

<div class="play" ng-click="animate($event)"></div>

js function (in controller):

$scope.animate = function(event) {
    var el = event.srcElement;
    angular.element(el).addClass('animate');
    $timeout(function() {
        angular.element(el).removeClass('animate');
    }, 1000);
};

CSS:

.play.animate {
  animation:0.5s bounceIn ease;
}

I don't particularly love the use of timeout here to remove the class after the animation should be complete. Is ngClick even the answer here, or should I be using a totally custom directive?

Answers


t3__rry February 2016

You can set up a variable in your controller:

    this.animated = false;
    this.animationToggle = function(){
        this.animated = !this.animated;
    };

And inside your element change the value on click and conditionaly add you class:

<div ng-class="{'play' : ctrl.animated}" ng-click="ctrl.animationToggle()"></div>

Post Status

Asked in February 2016
Viewed 1,308 times
Voted 4
Answered 1 times

Search




Leave an answer


Quote of the day: live life