Custom Animations with ng-animate $animate

非 Y 不嫁゛ 提交于 2019-12-24 05:30:57

问题


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()



来源:https://stackoverflow.com/questions/29959542/custom-animations-with-ng-animate-animate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!