Search code examples
htmlcssangularjsangularjs-ng-clickng-class

ng-class remove class after set time


I'm trying to create a quick animation demo with a button that adds a class on a container to play animation using ng-click. What I want to do is to remove the applied class after a set period of time. Can you please tell me why the following code is not working :$ ?

    <!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>

Solution

  • Firstly you need to bind values to $scope:

    $scope.trigger = 0;
    

    You also need to use $timeout instead of setTimeout() so that bindings are updated:

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

    Then you can set your button html like this for example:

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