Custom animations with ng-animate $ animate

I need help improving my understanding of custom animations in AngularJS 1.3.

purpose

  • Click an item
  • Animating a single element in the DOM

I created the following plunkr with no success

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

    <!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">

    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.js"></script>

    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular-animate.min.js"></script>

    <script src="script.js"></script>

  </head>

  <body ng-app="app">
    <ul>
      <li animate-trigger> Click on me to animate </li>
    </ul>

    <div  class="divtoanimate animated">
      Animate Action Baby
    </div>


  </body>

</html>

      

Js

'use strict';
var app = angular.module('app', ['ngAnimate'])

app.directive('animateTrigger', ['$animate', function ($animate) {

    return function (scope, elem, attrs) {

        elem.on('click', function (elem) {

            var el = angular.element(document.getElementsByClassName("divtoanimate"));
            console.log("clicked");
            var promise = $animate.addClass(el, "bounceIn");

            promise.then(function () {
                $animate.removeClass(el, "bounceIn");
            });

        });

    }

}]);

      

+2


source to share


2 answers


Use $ scope.apply for the initial animation and inside your promise to both add and remove classes. Check out the code below and the attached plunkr, which demonstrates the animation repeating each time a trigger animation button is pressed.

work-plunkr



var app = angular.module('app', ['ngAnimate'])

app.directive('animateTrigger', ['$animate', function ($animate) {

  return function (scope, elem, attrs) {
    elem.on('click', function (elem) {
      scope.$apply(function() {
        var el = angular.element(document.getElementsByClassName("divtoanimate"));
        var promise = $animate.addClass(el, "bounceIn");
        promise.then(function () {
          scope.$apply(function() {
            $animate.removeClass(el, "bounceIn");
          });
        });
      });
    });
  }
}]);

      

+3


source


Since you are using a jquery event handler, you need to call scope.$apply(function() {...})

to make your $ animate calls.

Here's the plunkr updated with scope.$apply

:

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



More about scope.$apply

:

https://github.com/angular/angular.js/wiki/When-to-use- $ scope. $ apply ()

+1


source







All Articles