Custom Animations with ng-animate $animate

2019-07-18 23:11发布

问题:

I need some help on better understanding custom animations in AngularJS 1.3.

The objective

  • Click on an element
  • Animate separate element on the DOM

I have 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");
            });

        });

    }

}]);

回答1:

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

working-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");
          });
        });
      });
    });
  }
}]);


回答2:

Since you're using the jquery event handler, you need to call scope.$apply(function() {...}) to perform your $animate calls.

Here's plunkr updated with scope.$apply:

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

More on scope.$apply:

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