Using AngularJS' ngAnimate when removing an item from scope
Asked Answered
M

1

7

Very simple question: In AngularJS 1.2.x, is it possible (and how) to get ngAnimate to fire when removing an item from scope?

Here's an example Plunker:

http://plnkr.co/edit/tpl:FrTqqTNoY8BEfHs9bB0f?p=preview

Code:

  <body ng-controller="MainCtrl">  
      <div ng-repeat="img in imgs" class="my-repeat-animation">
        <img ng-src="{{img}}" />
        <button class="btn btn-primary" ng-click="remove(img)">DELETE</button>
      </div>
  </body>

Script:

app.controller('MainCtrl', function($scope) {
     $scope.imgs = ['http://cache.mrporter.com/images/products/362812/362812_mrp_in_l.jpg', 'http://cache.mrporter.com/images/products/362807/362807_mrp_in_l.jpg', 'http://cache.mrporter.com/images/products/364762/364762_mrp_in_l.jpg', 'http://cache.mrporter.com/images/products/357020/357020_mrp_in_l.jpg']
     $scope.remove = function(image){
       var index = $scope.imgs.indexOf(image);
       $scope.imgs.splice(index,1);
     }
});

As you can see, clicking the "DELETE" button runs splice() on $scope.imgs. I'd like to animate this, rather than have it simply disappear. I'm using the transitions just copy-and-pasted from this Year Of Moo article which works just fine when filtering the scope, but evidently not when removing from scope.

Mottled answered 12/11, 2013 at 6:34 Comment(1)
I don't think this is the link to the correct plunker.Schmitt
C
9

Make sure app includes ngAnimate as a dependency, the file angular-animate.js is loaded after angular.js, and add this example animation to your CSS:

/* Add animation */
.my-repeat-animation.ng-enter.ng-enter-active, 
.my-repeat-animation.ng-leave {
    opacity: 1;
    -webkit-transition: opacity 300ms linear;
    -moz-transition: opacity 300ms linear;
    transition: opacity 300ms linear;
}

/* Remove animation */
.my-repeat-animation.ng-leave.ng-leave-active, 
.my-repeat-animation.ng-enter {
    opacity: 0;
    -webkit-transition: opacity 300ms linear;
    -moz-transition: opacity 300ms linear;
    transition: opacity 300ms linear;
}

This will animate both additions to, and removals from imgs.

Cretonne answered 2/12, 2013 at 11:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.