最初隐藏元素时,角度动画在首次运行时无法正常工作

时间:2014-04-16 23:22:20

标签: angularjs ng-animate

我在我的角度应用程序上连接状态栏,目的是当向服务器发出请求时,栏会显示响应消息,将有背景颜色来表示成功或错误,以及是否成功几秒钟后隐藏起来。

我所看到的是,在加载页面后第一次运行此逻辑时,动画未运行(淡入和定时淡出都无法运行),但仅当状态栏元素最初被隐藏时,如果我在页面加载时将ng-show变量设置为true,则所有动画都按预期工作。

我确实通过chrome的开发人员工具检查了源代码,并且在第一次运行期间,div应该在完成动画之后具有这些类alert-bar ng-hide-remove ng-hide-remove-active alert-bar-success ng-animate ng-hide。当动画确实有效时,唯一存在的类是alert-bar alert-bar-success ng-animate ng-hide

HTML:

<div class="alert-bar" ng-show="response.show"  ng-class="(response.result == true) ? 'alert-bar-success' : 'alert-bar-danger'">
    <div class="container">
        <label>Message: {{response.message}}</label>
    </div>
</div>

CSS:

.alert-bar {
    width: 100%;
    margin-top: -20px;
    margin-bottom: 20px;
}

.alert-bar-success {
    background-color: #5cb85c;
    border-color: #4cae4c;
    color: #ffffff;
}

.alert-bar-danger {
    color: #ffffff;
    background-color: #d9534f;
    border-color: #d43f3a;
}

.alert-bar.ng-hide-add, .alert-bar.ng-hide-remove {
  -webkit-transition:all linear 0.3s;
  -moz-transition:all linear 0.3s;
  -o-transition:all linear 0.3s;
  transition:all linear 0.3s;
  display:block!important;
}

.alert-bar.ng-hide-add.ng-hide-add-active,
.alert-bar.ng-hide-remove {
  opacity:0;
}

.alert-bar.ng-hide-add,
.alert-bar.ng-hide-remove.ng-hide-remove-active {
  opacity:1;
}

控制器:

controllers.controller("AppController", ['$scope', '$timeout', function($scope, $timeout) {
    $scope.response = {};

    $scope.response.received = function(message, result) {
        $scope.response.message = message;
        $scope.response.result = result;
        $scope.response.show = true;
        if (result == true) {
            $timeout(function () {
                $scope.response.show = false;
            }, 4000);
        }
    };
}]);

2 个答案:

答案 0 :(得分:8)

这是由于应用于ng-classng-hide指令的动画代码之间的相互作用而发生的。我做这样的工作的唯一方法是使用单独的<div>元素,这些元素有条件地显示/隐藏但具有静态类。

这是一个plunkr,它演示了如何将上述内容拆分为两个<div>元素,以便为问题中的问题创建一个工作示例:

http://plnkr.co/edit/PFNGkOLKvs8Gx9h1T6Yk?p=preview

或者,您可以完全放弃使用ng-hide / ng-show并完全使用ng-class

修改:有关仅使用ng-class的版本,请参阅http://plnkr.co/edit/JiLPc6cqiLHR21c64cCy?p=preview

答案 1 :(得分:1)

您不需要使用两个div。我想最简单的解决方案就是将动画css仅放入“ng-hide-add-active”类,而不是“ng-hide-add”。如下所示:

.page-ready-animate.ng-hide-add-active {
  -webkit-animation: 0.5s fadeOutDown;
  animation: 0.5s fadeOutDown;
}
相关问题