0

While trying to build an animation based on velocity.js with AngularJS $animate, I encountered a small problem I couldn't figure for hours, although the solution was very simple. To avoid you the same difficulty, I present to you my solution:

Considering the following code:

app.directive("animate", function ($animate, $timeout) {
    return function (scope, element, attrs) {
        element.on('click', function () {
            // to fire $animate, need to wrap it into a $timeout wrapper.
            $timeout(function () {
                $animate.addClass(element, 'test').then(function () {
                    $timeout(function () {
                        $animate.removeClass(element, 'test');
                    }, 0);
                });
            }, attrs.delay || 0);
        });
    };
});
4
  • Just wanted to note I flagged this for "moderator" attention. I think this is probably valuable for someone, but needs to be re-phrased in terms of question and answer instead of it all being in the question section. Commented Dec 9, 2014 at 13:37
  • Thx for the flag ! First post over there so quite ignorant of the best practices :) Commented Dec 9, 2014 at 15:12
  • I just don't want people to come in a close it out. The information is valuable, but just needs to be broken out. I don't think only a moderator can do that... Commented Dec 9, 2014 at 16:15
  • 1
    You can (and should) post your own answer with the solution in it rather than mix the question and answer together. Commented Dec 10, 2014 at 10:21

1 Answer 1

1

$animate returns a promise, according to the official documentation. But to fire this promise when the custom animation is actually finished, you must use the done() function provided as third argument such as below :

app.animation('.test', function () {
    var fn = function (element, className, done) {
        var effect = {
            css: {
                translateX:'+=500'
            },
            options: {
                easing: 'linear',
                duration: 2000,
                complete: function () {done();}
            }
        };

        element.velocity(effect.css, effect.options);
    };

    return {
        addClass: fn,
        removeClass: function () {console.log('removed';}
    };
});

Little trick, so, but this prototype was missing from all the documentation and tutorial i found since now. Enjoy your third-party libraries animations with Angular.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.