javascript - AngularJS 动画回调,等待下一个动画开始

标签 javascript angularjs css angularjs-directive css-animations

我有一个简单的 AngularJS 元素,其中有一个指令,我想在另一个完成时启动 CSS 动画 - 希望我发送,我有一个 jsfiddle此处的示例,动画同时运行 - 我希望第一个“卡片”动画在下一个开始之前停止 - 如何才能做到这一点?

<div ng-app="flip" ng-controller="flipCtrl">
    <div class="card card1 draw" my-show="">test1</div>
    <div class="card card2 draw" my-show="">test2</div>
</div>

app.directive("myShow", function(){
  return {
    scope:{
      param: "&myShow"
    },
    link: function( scope, element, attrs ){
        element.on('click', function() {
            if(element.hasClass('draw')) {
                element.removeClass('draw');                
            }else{
                element.addClass('draw');
            }
        });
    }
  }
});

http://jsfiddle.net/9kanr29z/5/

最佳答案

首先,重要的是要记住包含 AngularJS 的版本。您正在使用。不过,我将提供 1.21.3+ 解决方案。如果您使用的版本低于 1.2,您应该真正考虑升级。

$animate 服务

$animate 服务提供了一个 addClass 方法和一个 removeClass 方法,可以轻松满足您的需求。行为会根据您使用的 AngularJS 版本而变化。

无论哪种方式,您都首先包含 animate 模块(它与 angular.js 主文件分开),然后在需要的地方注入(inject) $animate 服务。

app.directive("myShow", [
  '$animate',
  function($animate) {
    return {
      // your directive config
    };
  }
]);

AngularJS v1.2.x

$animate (v1.2.26)服务addClassremoveClass方法具有三个参数:element、className 和 didCallback。在这里,简单地说,您可以使用 doneCallback 函数参数来告知动画何时完成。例如:

$animate.addClass(element, 'draw', function() {
  // if we are in here, the animation is complete
});

AngularJS v1.3.x

With AngularJS 1.3, each of the animation methods, on the $animate service, return a promise when called. The promise itself is then resolved once the animation has completed itself, has been cancelled or has been skipped due to animations being disabled. (Note that even if the animation is cancelled it will still call the resolve function of the animation.) See Documentation

对于 1.3 及更高版本,您需要利用通过 $animate 服务调用 addClassremoveClass 返回的 promise 。您可以通过在末尾链接 then 函数来实现此目的。例如:

$animate.addClass(element, 'draw').then(function() {
  // if we are in here, the animation is complete
});

如果您使用的是 AngularJS 1.3 RC (截至本文最新不稳定)并且您不熟悉 Promise,那么请引用 $q服务。

关于javascript - AngularJS 动画回调,等待下一个动画开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26469511/

相关文章:

javascript - 在 Protractor 中做一个鼠标滚轮

javascript - AngularJS 对单击的 span 元素进行过滤会从表中删除数据

css - 当父级包含特定子级时如何设置父级样式?

javascript - 如何确保工厂 promise 在指令执行之前解决

javascript - angularjs 不安全的 Twitter 链接?

php - 加载页面时如何为html标签设置类?

css - 找不到模块 : Error: Can't resolve './style.css' in Directory?

javascript - 只获取选定的项目而不提交?

JavaScript 'hoisting'

javascript - 选择和 If 语句