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

1 回答 1

1

根据官方文档,$animate 返回一个承诺。但是要在自定义动画实际完成时触发此承诺,您必须使用done()作为第三个参数提供的函数,如下所示:

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';}
    };
});

所以,小技巧,但是从现在开始我发现的所有文档和教程中都缺少这个原型。使用 Angular 享受您的第三方库动画。

于 2014-12-11T10:26:40.310 回答