Ng-class - remove a class after it is added to the DOM

masanorinyo picture masanorinyo · Apr 17, 2014 · Viewed 16k times · Source

I am using animate.css to make animation on the same element. I am having a problem in removing the class after adding it.

HTML

 <form ng-submit="animate()" ng-controller="AnimateCtrl">
    <input type='text' ng-model="some">
 </form>
 <div ng-class="{shake:animation.shake}" class="animated">

Angular

myapp.controller(function($scope){
     var animation = $scope.animation = {
           shake:false
     };

     $scope.animate=function(){

         //remove the class first and add it back again

          animation.shake = false

          animation.shake = true


     };

})

How can I remove the class after animation?

Answer

mccainz picture mccainz · Apr 17, 2014

Changing the value of animation.shake to false removes the class. Changing it to true adds the class. That is the foundation of how ng-class works. If you are wanting your animation to run for some interval you need to toggle using $timeout. Difficult to tell by your code. The following example removes the class using a $timeout which executes after 2000 milliseconds.

For example http://plnkr.co/edit/Wtxkrv2nIqSLNfEsvCyI?p=preview

CSS .red{ color:red; }

HTML And Code

<!DOCTYPE html>
<html>

<head>
<script data-require="angular.js@*" data-semver="1.2.16" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>

<body ng-controller="test">
<h1>Hello Plunker!</h1>
<span ng-class="{'red':animation.shake}">Hello World</span>
<button ng-click="shake()">red</button>
<script>

  var app=angular.module("app",[]);
  app.controller("test",function($scope,$timeout){
    $scope.animation={shake:false};
    $scope.shake=function(){
      $scope.animation.shake=true;
      $timeout(function(){
        $scope.animation.shake=false;
      },2000,true);
    }
  });
  angular.bootstrap(document,["app"]);
</script>