关于angularjs:带有ng-animate $ animate的自定义动画

Custom Animations with ng-animate $animate

我需要一些帮助来更好地了解AngularJS 1.3中的自定义动画。

目标

  • 点击一个元素
  • 对DOM上的单独元素进行动画处理

我创建了以下失败代码,但没有成功

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
    <!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 src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular-animate.min.js">

    <script src="script.js">

  </head>

  <body ng-app="app">
   
<ul>

      <li animate-trigger> Click on me to animate
</li>

   
</ul>


   
      Animate Action Baby
   


  </body>

</html>

JS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
'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");
            });

        });

    }

}]);

将$ scope.apply用于初始动画,并在您的诺言中添加和删除类。 请查看下面的代码和随附的plunkr,该代码演示了每次单击animage-trigger指令时重复播放的动画。

工作朋克

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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");
          });
        });
      });
    });
  }
}]);

由于您正在使用jquery事件处理程序,因此需要调用scope.$apply(function() {...})来执行$ animate调用。

这是用scope.$apply更新的plunkr:

http://plnkr.co/edit/qOhLWze8pGkO9dGRp1Sg?p=预览

关于scope.$apply的更多信息:

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