Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using AngularJS' ngAnimate when removing an item from scope

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.

like image 944
JVG Avatar asked Nov 12 '13 06:11

JVG


1 Answers

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.

like image 184
Blaise Avatar answered Oct 02 '22 18:10

Blaise