Running code after an AngularJS animation has completed

前端 未结 3 946
醉梦人生
醉梦人生 2020-12-07 23:11

I have an element whose visibility is toggled by ng-show. I\'m also using CSS animations - the automatic ones from ng-animate - on this element to animate its e

3条回答
  •  忘掉有多难
    2020-12-07 23:28

    As @zeroflagL has suggested, a custom directive to replace ngShow is probably the way to go. You can use & to pass callbacks into the directive, which can be called after the animations have finished. For consistency, the animations are done by adding and removing the ng-hide class, which is the same method used by the usual ngShow directive:

    app.directive('myShow', function($animate) {
      return {
        scope: {
          'myShow': '=',
          'afterShow': '&',
          'afterHide': '&'
        },
        link: function(scope, element) {
          scope.$watch('myShow', function(show, oldShow) {
            if (show) {
              $animate.removeClass(element, 'ng-hide', scope.afterShow);
            }
            if (!show) {
              $animate.addClass(element, 'ng-hide', scope.afterHide);
            }
          });
        }
      }
    })
    

    Example use of this listening to a scope variable show would be:

    ...

    Because this is adding/removing the ng-hide class, the points about animating from the docs about ngShow are still valid, and you need to add display: block !important to the CSS.

    You can see an example of this in action at this Plunker.

提交回复
热议问题