ng-class在设定时间后删除类

时间:2014-07-20 12:48:50

标签: html css angularjs angularjs-ng-click ng-class

我正在尝试使用按钮创建一个快速动画演示,该按钮在容器上添加一个类以使用ng-click播放动画。我想要做的是在一段时间后删除应用的类。你能否告诉我为什么以下代码不起作用:$?

    <!doctype html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
    <script type="text/javascript" src="script/angular.js"></script>

    <style>
        .animation-container {
            display: block;
            height:500px;
            padding: 10px;
            background: black;
            text-align: center;     }
        .animation-trigger {
            display: block;
            padding: 5px;
            background: #111;
            text-align: center;
        }

        .box {
            display: inline-block;
            width: 150px;
            height: 150px;
            background: red;

            transition: all 1s ease;
        }

        .reload {
            width: 150px;
            height: 150px;
        }

        .play {
            width: 250px;
            height: 250px;
        }
    </style>

    <script>
        var myApp = angular.module("myApp", []);
        myApp.controller("animationController", function($scope){
            this.trigger = 0;

            this.reset = function() { 
                setTimeout(function() { 
                    return this.trigger === 0;
                    }, 2000
                );
            }
        });
    </script>

</head>
<body ng-app="myApp">
<div class="animation-wrapper" ng-controller="animationController as anim">
    <div class="animation-container">
        <div class="box" ng-class="{play : anim.trigger === 1, reload : anim.trigger === 0}"></div>
    </div>

    <div class="animation-trigger">
        <button ng-click="anim.trigger = 1; anim.reset()" >Play Animation</button>
    </div>
</div>

</body>
</html>

1 个答案:

答案 0 :(得分:2)

首先,您需要将值绑定到$scope

$scope.trigger = 0;

您还需要使用$timeout代替setTimeout(),以便更新绑定:

$scope.reset = function() {
    $timeout(function(){
        $scope.trigger = 0;
    }, 2000);
};

然后你可以设置你的按钮html,例如:

<button ng-click="trigger = 1; reset()" >Play Animation</button>