AngularJS css animation + done callback

Yes you can, using the $animate service, which would usually be done in a custom directive. A simple case of animation would be to animate an element in some way on click. Say, for example to remove an element on click, with an animation specified using .ng-leave, passing a callback

app.directive('leaveOnClick', function($animate) {
  return {
    scope: {
      'leaveOnClick': '&'
    },
    link: function (scope, element) {
      scope.leaveOnClick = scope.leaveOnClick || (function() {});
      element.on('click', function() {
        scope.$apply(function() {
          $animate.leave(element, scope.leaveOnClick);
        });
      });
    }
  };
});

which could be used like:

<div class="my-div" leaveOnClick="done()">Click to remove</div>

With CSS to fade the element out:

.my-div.ng-leave {
  opacity: 1;
  transition: opacity 1s;
  -webkit-transition: opacity 1s;
}
.my-div.ng-leave.ng-leave-active {
  opacity: 0;
}

You can see the above animation in action at this Plunker.

However, ngIf doesn’t have any hooks to pass a callback in that I know of, so you’ll have to write your own directive. What follows is a description of a modified version of ngIf, originally copied from the ngIf source, and renamed to animatedIf. It can be used by:

<div class="my-div" animated-if="shown" animated-if-leave-callback="leaveDone()" animated-if-enter-callback="enterDone()" >Some content</div>

The way it works is that it uses a manual watcher to react to changes of the expression passed to animated-if. The key differences to the original ngIf are the addition of a ‘scope’ parameter to pass the callbacks in:

scope: {
  'animatedIf': '=',
  'animatedIfEnterCallback': '&',
  'animatedIfLeaveCallback': '&'
},

and then modifying the calls to $animate.enter and $animate.leave to call these callbacks after the animation:

var callback = !oldValue && $scope.animatedIfEnterCallback ? $scope.animatedIfEnterCallback : (function() {});
$animate.enter(clone, $element.parent(), $element, callback);

$animate.leave(block.clone, ($scope.animatedIfLeaveCallback || (function() {})));

The enter one is a bit more complicated to not call the callback on initial loading of the directive. Because of the scope parameter, this directive creates an isolated scope, which it then uses when transcluding the contents. So another change that is required is to create and use a scope as a child from the $parent scope of the directive: the line

 childScope = $scope.$new();

must be changed to

 childScope = $scope.$parent.$new();

You can see the full source of the modified ngIf directive in this Plunker. This has only been tested extremely briefly.

There may well be a simpler way of doing this, maybe by not recreating the ngIf directive fully, but creating a directive with template that uses the original ngIf with some wrapper divs, such as

template: '<div><div ng-if="localVariable"><div ng-transclude></div></div></div>'

Leave a Comment